es6.js 4.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635
  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. "use strict";
  4. var BABYLON;
  5. (function (BABYLON) {
  6. /**
  7. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  8. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  9. */
  10. var EffectFallbacks = /** @class */ (function () {
  11. function EffectFallbacks() {
  12. this._defines = {};
  13. this._currentRank = 32;
  14. this._maxRank = -1;
  15. }
  16. /**
  17. * Removes the fallback from the bound mesh.
  18. */
  19. EffectFallbacks.prototype.unBindMesh = function () {
  20. this._mesh = null;
  21. };
  22. /**
  23. * Adds a fallback on the specified property.
  24. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  25. * @param define The name of the define in the shader
  26. */
  27. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28. if (!this._defines[rank]) {
  29. if (rank < this._currentRank) {
  30. this._currentRank = rank;
  31. }
  32. if (rank > this._maxRank) {
  33. this._maxRank = rank;
  34. }
  35. this._defines[rank] = new Array();
  36. }
  37. this._defines[rank].push(define);
  38. };
  39. /**
  40. * Sets the mesh to use CPU skinning when needing to fallback.
  41. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  42. * @param mesh The mesh to use the fallbacks.
  43. */
  44. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  45. this._mesh = mesh;
  46. if (rank < this._currentRank) {
  47. this._currentRank = rank;
  48. }
  49. if (rank > this._maxRank) {
  50. this._maxRank = rank;
  51. }
  52. };
  53. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  54. /**
  55. * Checks to see if more fallbacks are still availible.
  56. */
  57. get: function () {
  58. return this._currentRank <= this._maxRank;
  59. },
  60. enumerable: true,
  61. configurable: true
  62. });
  63. /**
  64. * Removes the defines that shoould be removed when falling back.
  65. * @param currentDefines defines the current define statements for the shader.
  66. * @param effect defines the current effect we try to compile
  67. * @returns The resulting defines with defines of the current rank removed.
  68. */
  69. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  70. // First we try to switch to CPU skinning
  71. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  72. this._mesh.computeBonesUsingShaders = false;
  73. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. this._uniformBuffersNames = {};
  163. this._isReady = false;
  164. this._compilationError = "";
  165. this.name = baseName;
  166. if (attributesNamesOrOptions.attributes) {
  167. var options = attributesNamesOrOptions;
  168. this._engine = uniformsNamesOrEngine;
  169. this._attributesNames = options.attributes;
  170. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  171. this._samplers = options.samplers;
  172. this.defines = options.defines;
  173. this.onError = options.onError;
  174. this.onCompiled = options.onCompiled;
  175. this._fallbacks = options.fallbacks;
  176. this._indexParameters = options.indexParameters;
  177. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  178. if (options.uniformBuffersNames) {
  179. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  180. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  181. }
  182. }
  183. }
  184. else {
  185. this._engine = engine;
  186. this.defines = defines;
  187. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  188. this._samplers = samplers;
  189. this._attributesNames = attributesNamesOrOptions;
  190. this.onError = onError;
  191. this.onCompiled = onCompiled;
  192. this._indexParameters = indexParameters;
  193. this._fallbacks = fallbacks;
  194. }
  195. this.uniqueId = Effect._uniqueIdSeed++;
  196. if (this._getFromCache(baseName)) {
  197. this._prepareEffect();
  198. return;
  199. }
  200. var vertexSource;
  201. var fragmentSource;
  202. if (baseName.vertexElement) {
  203. vertexSource = document.getElementById(baseName.vertexElement);
  204. if (!vertexSource) {
  205. vertexSource = baseName.vertexElement;
  206. }
  207. }
  208. else {
  209. vertexSource = baseName.vertex || baseName;
  210. }
  211. if (baseName.fragmentElement) {
  212. fragmentSource = document.getElementById(baseName.fragmentElement);
  213. if (!fragmentSource) {
  214. fragmentSource = baseName.fragmentElement;
  215. }
  216. }
  217. else {
  218. fragmentSource = baseName.fragment || baseName;
  219. }
  220. var finalVertexCode;
  221. this._loadVertexShaderAsync(vertexSource)
  222. .then(function (vertexCode) {
  223. return _this._processIncludesAsync(vertexCode);
  224. })
  225. .then(function (vertexCodeWithIncludes) {
  226. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  227. return _this._loadFragmentShaderAsync(fragmentSource);
  228. })
  229. .then(function (fragmentCode) {
  230. return _this._processIncludesAsync(fragmentCode);
  231. })
  232. .then(function (fragmentCodeWithIncludes) {
  233. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  234. if (baseName) {
  235. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  236. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  237. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  238. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  239. }
  240. else {
  241. _this._vertexSourceCode = finalVertexCode;
  242. _this._fragmentSourceCode = migratedFragmentCode;
  243. }
  244. _this._setInCache(baseName);
  245. _this._prepareEffect();
  246. });
  247. }
  248. Effect.prototype._getSourceCacheKey = function (baseName) {
  249. var cacheKey = baseName;
  250. if (this._indexParameters) {
  251. for (var key in this._indexParameters) {
  252. if (this._indexParameters.hasOwnProperty(key)) {
  253. cacheKey += "|";
  254. cacheKey += key;
  255. cacheKey += "_";
  256. cacheKey += this._indexParameters[key];
  257. }
  258. }
  259. }
  260. return cacheKey;
  261. };
  262. Effect.prototype._getFromCache = function (baseName) {
  263. if (typeof baseName !== "string") {
  264. return false;
  265. }
  266. var cacheKey = this._getSourceCacheKey(baseName);
  267. var sources = Effect._sourceCache[cacheKey];
  268. if (!sources) {
  269. return false;
  270. }
  271. this._vertexSourceCode = sources.vertex;
  272. this._fragmentSourceCode = sources.fragment;
  273. return true;
  274. };
  275. Effect.prototype._setInCache = function (baseName) {
  276. if (typeof baseName !== "string") {
  277. return;
  278. }
  279. var cacheKey = this._getSourceCacheKey(baseName);
  280. Effect._sourceCache[cacheKey] = {
  281. vertex: this._vertexSourceCode,
  282. fragment: this._fragmentSourceCode
  283. };
  284. };
  285. Object.defineProperty(Effect.prototype, "key", {
  286. /**
  287. * Unique key for this effect
  288. */
  289. get: function () {
  290. return this._key;
  291. },
  292. enumerable: true,
  293. configurable: true
  294. });
  295. /**
  296. * If the effect has been compiled and prepared.
  297. * @returns if the effect is compiled and prepared.
  298. */
  299. Effect.prototype.isReady = function () {
  300. return this._isReady;
  301. };
  302. /**
  303. * The engine the effect was initialized with.
  304. * @returns the engine.
  305. */
  306. Effect.prototype.getEngine = function () {
  307. return this._engine;
  308. };
  309. /**
  310. * The compiled webGL program for the effect
  311. * @returns the webGL program.
  312. */
  313. Effect.prototype.getProgram = function () {
  314. return this._program;
  315. };
  316. /**
  317. * The set of names of attribute variables for the shader.
  318. * @returns An array of attribute names.
  319. */
  320. Effect.prototype.getAttributesNames = function () {
  321. return this._attributesNames;
  322. };
  323. /**
  324. * Returns the attribute at the given index.
  325. * @param index The index of the attribute.
  326. * @returns The location of the attribute.
  327. */
  328. Effect.prototype.getAttributeLocation = function (index) {
  329. return this._attributes[index];
  330. };
  331. /**
  332. * Returns the attribute based on the name of the variable.
  333. * @param name of the attribute to look up.
  334. * @returns the attribute location.
  335. */
  336. Effect.prototype.getAttributeLocationByName = function (name) {
  337. var index = this._attributesNames.indexOf(name);
  338. return this._attributes[index];
  339. };
  340. /**
  341. * The number of attributes.
  342. * @returns the numnber of attributes.
  343. */
  344. Effect.prototype.getAttributesCount = function () {
  345. return this._attributes.length;
  346. };
  347. /**
  348. * Gets the index of a uniform variable.
  349. * @param uniformName of the uniform to look up.
  350. * @returns the index.
  351. */
  352. Effect.prototype.getUniformIndex = function (uniformName) {
  353. return this._uniformsNames.indexOf(uniformName);
  354. };
  355. /**
  356. * Returns the attribute based on the name of the variable.
  357. * @param uniformName of the uniform to look up.
  358. * @returns the location of the uniform.
  359. */
  360. Effect.prototype.getUniform = function (uniformName) {
  361. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  362. };
  363. /**
  364. * Returns an array of sampler variable names
  365. * @returns The array of sampler variable neames.
  366. */
  367. Effect.prototype.getSamplers = function () {
  368. return this._samplers;
  369. };
  370. /**
  371. * The error from the last compilation.
  372. * @returns the error string.
  373. */
  374. Effect.prototype.getCompilationError = function () {
  375. return this._compilationError;
  376. };
  377. /**
  378. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  379. * @param func The callback to be used.
  380. */
  381. Effect.prototype.executeWhenCompiled = function (func) {
  382. if (this.isReady()) {
  383. func(this);
  384. return;
  385. }
  386. this.onCompileObservable.add(function (effect) {
  387. func(effect);
  388. });
  389. };
  390. /** @ignore */
  391. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  392. if (BABYLON.Tools.IsWindowObjectExist()) {
  393. // DOM element ?
  394. if (vertex instanceof HTMLElement) {
  395. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  396. return Promise.resolve(vertexCode);
  397. }
  398. }
  399. // Base64 encoded ?
  400. if (vertex.substr(0, 7) === "base64:") {
  401. var vertexBinary = window.atob(vertex.substr(7));
  402. return Promise.resolve(vertexBinary);
  403. }
  404. // Is in local store ?
  405. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  406. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  407. }
  408. var vertexShaderUrl;
  409. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  410. vertexShaderUrl = vertex;
  411. }
  412. else {
  413. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  414. }
  415. // Vertex shader
  416. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  417. };
  418. /** @ignore */
  419. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  420. if (BABYLON.Tools.IsWindowObjectExist()) {
  421. // DOM element ?
  422. if (fragment instanceof HTMLElement) {
  423. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  424. return Promise.resolve(fragmentCode);
  425. }
  426. }
  427. // Base64 encoded ?
  428. if (fragment.substr(0, 7) === "base64:") {
  429. var fragmentBinary = window.atob(fragment.substr(7));
  430. return Promise.resolve(fragmentBinary);
  431. }
  432. // Is in local store ?
  433. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  434. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  435. }
  436. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  437. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  438. }
  439. var fragmentShaderUrl;
  440. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  441. fragmentShaderUrl = fragment;
  442. }
  443. else {
  444. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  445. }
  446. // Fragment shader
  447. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  448. };
  449. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  450. // Rebuild shaders source code
  451. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  452. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  453. vertexCode = prefix + vertexCode;
  454. fragmentCode = prefix + fragmentCode;
  455. // Number lines of shaders source code
  456. var i = 2;
  457. var regex = /\n/gm;
  458. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  459. i = 2;
  460. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  461. // Dump shaders name and formatted source code
  462. if (this.name.vertexElement) {
  463. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  464. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  465. }
  466. else if (this.name.vertex) {
  467. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  468. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  469. }
  470. else {
  471. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  472. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  473. }
  474. };
  475. ;
  476. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  477. var preparedSourceCode = this._processPrecision(sourceCode);
  478. if (this._engine.webGLVersion == 1) {
  479. return preparedSourceCode;
  480. }
  481. // Already converted
  482. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  483. return preparedSourceCode.replace("#version 300 es", "");
  484. }
  485. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  486. // Remove extensions
  487. // #extension GL_OES_standard_derivatives : enable
  488. // #extension GL_EXT_shader_texture_lod : enable
  489. // #extension GL_EXT_frag_depth : enable
  490. // #extension GL_EXT_draw_buffers : require
  491. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  492. var result = preparedSourceCode.replace(regex, "");
  493. // Migrate to GLSL v300
  494. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  495. result = result.replace(/attribute[ \t]/g, "in ");
  496. result = result.replace(/[ \t]attribute/g, " in");
  497. if (isFragment) {
  498. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  499. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  500. result = result.replace(/texture2D\s*\(/g, "texture(");
  501. result = result.replace(/textureCube\s*\(/g, "texture(");
  502. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  503. result = result.replace(/gl_FragColor/g, "glFragColor");
  504. result = result.replace(/gl_FragData/g, "glFragData");
  505. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  506. }
  507. return result;
  508. };
  509. Effect.prototype._processIncludesAsync = function (sourceCode) {
  510. var _this = this;
  511. return new Promise(function (resolve, reject) {
  512. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  513. var match = regex.exec(sourceCode);
  514. var returnValue = sourceCode;
  515. while (match != null) {
  516. var includeFile = match[1];
  517. // Uniform declaration
  518. if (includeFile.indexOf("__decl__") !== -1) {
  519. includeFile = includeFile.replace(/__decl__/, "");
  520. if (_this._engine.supportsUniformBuffers) {
  521. includeFile = includeFile.replace(/Vertex/, "Ubo");
  522. includeFile = includeFile.replace(/Fragment/, "Ubo");
  523. }
  524. includeFile = includeFile + "Declaration";
  525. }
  526. if (Effect.IncludesShadersStore[includeFile]) {
  527. // Substitution
  528. var includeContent = Effect.IncludesShadersStore[includeFile];
  529. if (match[2]) {
  530. var splits = match[3].split(",");
  531. for (var index = 0; index < splits.length; index += 2) {
  532. var source = new RegExp(splits[index], "g");
  533. var dest = splits[index + 1];
  534. includeContent = includeContent.replace(source, dest);
  535. }
  536. }
  537. if (match[4]) {
  538. var indexString = match[5];
  539. if (indexString.indexOf("..") !== -1) {
  540. var indexSplits = indexString.split("..");
  541. var minIndex = parseInt(indexSplits[0]);
  542. var maxIndex = parseInt(indexSplits[1]);
  543. var sourceIncludeContent = includeContent.slice(0);
  544. includeContent = "";
  545. if (isNaN(maxIndex)) {
  546. maxIndex = _this._indexParameters[indexSplits[1]];
  547. }
  548. for (var i = minIndex; i < maxIndex; i++) {
  549. if (!_this._engine.supportsUniformBuffers) {
  550. // Ubo replacement
  551. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  552. return p1 + "{X}";
  553. });
  554. }
  555. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  556. }
  557. }
  558. else {
  559. if (!_this._engine.supportsUniformBuffers) {
  560. // Ubo replacement
  561. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  562. return p1 + "{X}";
  563. });
  564. }
  565. includeContent = includeContent.replace(/\{X\}/g, indexString);
  566. }
  567. }
  568. // Replace
  569. returnValue = returnValue.replace(match[0], includeContent);
  570. }
  571. else {
  572. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  573. _this._engine._loadFileAsync(includeShaderUrl)
  574. .then(function (fileContent) {
  575. Effect.IncludesShadersStore[includeFile] = fileContent;
  576. return _this._processIncludesAsync(returnValue);
  577. })
  578. .then(function (returnValue) {
  579. resolve(returnValue);
  580. });
  581. return;
  582. }
  583. match = regex.exec(sourceCode);
  584. }
  585. resolve(returnValue);
  586. });
  587. };
  588. Effect.prototype._processPrecision = function (source) {
  589. if (source.indexOf("precision highp float") === -1) {
  590. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  591. source = "precision mediump float;\n" + source;
  592. }
  593. else {
  594. source = "precision highp float;\n" + source;
  595. }
  596. }
  597. else {
  598. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  599. source = source.replace("precision highp float", "precision mediump float");
  600. }
  601. }
  602. return source;
  603. };
  604. /**
  605. * Recompiles the webGL program
  606. * @param vertexSourceCode The source code for the vertex shader.
  607. * @param fragmentSourceCode The source code for the fragment shader.
  608. * @param onCompiled Callback called when completed.
  609. * @param onError Callback called on error.
  610. */
  611. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  612. var _this = this;
  613. this._isReady = false;
  614. this._vertexSourceCodeOverride = vertexSourceCode;
  615. this._fragmentSourceCodeOverride = fragmentSourceCode;
  616. this.onError = function (effect, error) {
  617. if (onError) {
  618. onError(error);
  619. }
  620. };
  621. this.onCompiled = function () {
  622. var scenes = _this.getEngine().scenes;
  623. for (var i = 0; i < scenes.length; i++) {
  624. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  625. }
  626. if (onCompiled) {
  627. onCompiled(_this._program);
  628. }
  629. };
  630. this._fallbacks = null;
  631. this._prepareEffect();
  632. };
  633. /**
  634. * Gets the uniform locations of the the specified variable names
  635. * @param names THe names of the variables to lookup.
  636. * @returns Array of locations in the same order as variable names.
  637. */
  638. Effect.prototype.getSpecificUniformLocations = function (names) {
  639. var engine = this._engine;
  640. return engine.getUniforms(this._program, names);
  641. };
  642. /**
  643. * Prepares the effect
  644. */
  645. Effect.prototype._prepareEffect = function () {
  646. var attributesNames = this._attributesNames;
  647. var defines = this.defines;
  648. var fallbacks = this._fallbacks;
  649. this._valueCache = {};
  650. var previousProgram = this._program;
  651. try {
  652. var engine = this._engine;
  653. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  654. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  655. }
  656. else {
  657. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  658. }
  659. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  660. if (engine.supportsUniformBuffers) {
  661. for (var name in this._uniformBuffersNames) {
  662. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  663. }
  664. }
  665. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  666. this._attributes = engine.getAttributes(this._program, attributesNames);
  667. var index;
  668. for (index = 0; index < this._samplers.length; index++) {
  669. var sampler = this.getUniform(this._samplers[index]);
  670. if (sampler == null) {
  671. this._samplers.splice(index, 1);
  672. index--;
  673. }
  674. }
  675. engine.bindSamplers(this);
  676. this._compilationError = "";
  677. this._isReady = true;
  678. if (this.onCompiled) {
  679. this.onCompiled(this);
  680. }
  681. this.onCompileObservable.notifyObservers(this);
  682. this.onCompileObservable.clear();
  683. // Unbind mesh reference in fallbacks
  684. if (this._fallbacks) {
  685. this._fallbacks.unBindMesh();
  686. }
  687. if (previousProgram) {
  688. this.getEngine()._deleteProgram(previousProgram);
  689. }
  690. }
  691. catch (e) {
  692. this._compilationError = e.message;
  693. // Let's go through fallbacks then
  694. BABYLON.Tools.Error("Unable to compile effect:");
  695. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  696. return " " + uniform;
  697. }));
  698. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  699. return " " + attribute;
  700. }));
  701. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  702. BABYLON.Tools.Error("Error: " + this._compilationError);
  703. if (previousProgram) {
  704. this._program = previousProgram;
  705. this._isReady = true;
  706. if (this.onError) {
  707. this.onError(this, this._compilationError);
  708. }
  709. this.onErrorObservable.notifyObservers(this);
  710. }
  711. if (fallbacks && fallbacks.isMoreFallbacks) {
  712. BABYLON.Tools.Error("Trying next fallback.");
  713. this.defines = fallbacks.reduce(this.defines, this);
  714. this._prepareEffect();
  715. }
  716. else {
  717. if (this.onError) {
  718. this.onError(this, this._compilationError);
  719. }
  720. this.onErrorObservable.notifyObservers(this);
  721. this.onErrorObservable.clear();
  722. // Unbind mesh reference in fallbacks
  723. if (this._fallbacks) {
  724. this._fallbacks.unBindMesh();
  725. }
  726. }
  727. }
  728. };
  729. Object.defineProperty(Effect.prototype, "isSupported", {
  730. /**
  731. * Checks if the effect is supported. (Must be called after compilation)
  732. */
  733. get: function () {
  734. return this._compilationError === "";
  735. },
  736. enumerable: true,
  737. configurable: true
  738. });
  739. /**
  740. * Binds a texture to the engine to be used as output of the shader.
  741. * @param channel Name of the output variable.
  742. * @param texture Texture to bind.
  743. */
  744. Effect.prototype._bindTexture = function (channel, texture) {
  745. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  746. };
  747. /**
  748. * Sets a texture on the engine to be used in the shader.
  749. * @param channel Name of the sampler variable.
  750. * @param texture Texture to set.
  751. */
  752. Effect.prototype.setTexture = function (channel, texture) {
  753. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  754. };
  755. /**
  756. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  757. * @param channel Name of the sampler variable.
  758. * @param texture Texture to set.
  759. */
  760. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  761. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  762. };
  763. /**
  764. * Sets an array of textures on the engine to be used in the shader.
  765. * @param channel Name of the variable.
  766. * @param textures Textures to set.
  767. */
  768. Effect.prototype.setTextureArray = function (channel, textures) {
  769. if (this._samplers.indexOf(channel + "Ex") === -1) {
  770. var initialPos = this._samplers.indexOf(channel);
  771. for (var index = 1; index < textures.length; index++) {
  772. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  773. }
  774. }
  775. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  776. };
  777. /**
  778. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  779. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  780. * @param channel Name of the sampler variable.
  781. * @param postProcess Post process to get the input texture from.
  782. */
  783. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  784. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  785. };
  786. /**
  787. * Sets the output texture of the passed in post process to be input of this effect.
  788. * @param channel Name of the sampler variable.
  789. * @param postProcess Post process to get the output texture from.
  790. */
  791. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  792. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  793. };
  794. /** @ignore */
  795. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  796. var cache = this._valueCache[uniformName];
  797. var flag = matrix.updateFlag;
  798. if (cache !== undefined && cache === flag) {
  799. return false;
  800. }
  801. this._valueCache[uniformName] = flag;
  802. return true;
  803. };
  804. /** @ignore */
  805. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  806. var cache = this._valueCache[uniformName];
  807. if (!cache) {
  808. cache = [x, y];
  809. this._valueCache[uniformName] = cache;
  810. return true;
  811. }
  812. var changed = false;
  813. if (cache[0] !== x) {
  814. cache[0] = x;
  815. changed = true;
  816. }
  817. if (cache[1] !== y) {
  818. cache[1] = y;
  819. changed = true;
  820. }
  821. return changed;
  822. };
  823. /** @ignore */
  824. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  825. var cache = this._valueCache[uniformName];
  826. if (!cache) {
  827. cache = [x, y, z];
  828. this._valueCache[uniformName] = cache;
  829. return true;
  830. }
  831. var changed = false;
  832. if (cache[0] !== x) {
  833. cache[0] = x;
  834. changed = true;
  835. }
  836. if (cache[1] !== y) {
  837. cache[1] = y;
  838. changed = true;
  839. }
  840. if (cache[2] !== z) {
  841. cache[2] = z;
  842. changed = true;
  843. }
  844. return changed;
  845. };
  846. /** @ignore */
  847. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  848. var cache = this._valueCache[uniformName];
  849. if (!cache) {
  850. cache = [x, y, z, w];
  851. this._valueCache[uniformName] = cache;
  852. return true;
  853. }
  854. var changed = false;
  855. if (cache[0] !== x) {
  856. cache[0] = x;
  857. changed = true;
  858. }
  859. if (cache[1] !== y) {
  860. cache[1] = y;
  861. changed = true;
  862. }
  863. if (cache[2] !== z) {
  864. cache[2] = z;
  865. changed = true;
  866. }
  867. if (cache[3] !== w) {
  868. cache[3] = w;
  869. changed = true;
  870. }
  871. return changed;
  872. };
  873. /**
  874. * Binds a buffer to a uniform.
  875. * @param buffer Buffer to bind.
  876. * @param name Name of the uniform variable to bind to.
  877. */
  878. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  879. var bufferName = this._uniformBuffersNames[name];
  880. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  881. return;
  882. }
  883. Effect._baseCache[bufferName] = buffer;
  884. this._engine.bindUniformBufferBase(buffer, bufferName);
  885. };
  886. /**
  887. * Binds block to a uniform.
  888. * @param blockName Name of the block to bind.
  889. * @param index Index to bind.
  890. */
  891. Effect.prototype.bindUniformBlock = function (blockName, index) {
  892. this._engine.bindUniformBlock(this._program, blockName, index);
  893. };
  894. /**
  895. * Sets an interger value on a uniform variable.
  896. * @param uniformName Name of the variable.
  897. * @param value Value to be set.
  898. * @returns this effect.
  899. */
  900. Effect.prototype.setInt = function (uniformName, value) {
  901. var cache = this._valueCache[uniformName];
  902. if (cache !== undefined && cache === value)
  903. return this;
  904. this._valueCache[uniformName] = value;
  905. this._engine.setInt(this.getUniform(uniformName), value);
  906. return this;
  907. };
  908. /**
  909. * Sets an int array on a uniform variable.
  910. * @param uniformName Name of the variable.
  911. * @param array array to be set.
  912. * @returns this effect.
  913. */
  914. Effect.prototype.setIntArray = function (uniformName, array) {
  915. this._valueCache[uniformName] = null;
  916. this._engine.setIntArray(this.getUniform(uniformName), array);
  917. return this;
  918. };
  919. /**
  920. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  921. * @param uniformName Name of the variable.
  922. * @param array array to be set.
  923. * @returns this effect.
  924. */
  925. Effect.prototype.setIntArray2 = function (uniformName, array) {
  926. this._valueCache[uniformName] = null;
  927. this._engine.setIntArray2(this.getUniform(uniformName), array);
  928. return this;
  929. };
  930. /**
  931. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  932. * @param uniformName Name of the variable.
  933. * @param array array to be set.
  934. * @returns this effect.
  935. */
  936. Effect.prototype.setIntArray3 = function (uniformName, array) {
  937. this._valueCache[uniformName] = null;
  938. this._engine.setIntArray3(this.getUniform(uniformName), array);
  939. return this;
  940. };
  941. /**
  942. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  943. * @param uniformName Name of the variable.
  944. * @param array array to be set.
  945. * @returns this effect.
  946. */
  947. Effect.prototype.setIntArray4 = function (uniformName, array) {
  948. this._valueCache[uniformName] = null;
  949. this._engine.setIntArray4(this.getUniform(uniformName), array);
  950. return this;
  951. };
  952. /**
  953. * Sets an float array on a uniform variable.
  954. * @param uniformName Name of the variable.
  955. * @param array array to be set.
  956. * @returns this effect.
  957. */
  958. Effect.prototype.setFloatArray = function (uniformName, array) {
  959. this._valueCache[uniformName] = null;
  960. this._engine.setFloatArray(this.getUniform(uniformName), array);
  961. return this;
  962. };
  963. /**
  964. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  965. * @param uniformName Name of the variable.
  966. * @param array array to be set.
  967. * @returns this effect.
  968. */
  969. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  970. this._valueCache[uniformName] = null;
  971. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  972. return this;
  973. };
  974. /**
  975. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  976. * @param uniformName Name of the variable.
  977. * @param array array to be set.
  978. * @returns this effect.
  979. */
  980. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  981. this._valueCache[uniformName] = null;
  982. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  983. return this;
  984. };
  985. /**
  986. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  987. * @param uniformName Name of the variable.
  988. * @param array array to be set.
  989. * @returns this effect.
  990. */
  991. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  992. this._valueCache[uniformName] = null;
  993. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  994. return this;
  995. };
  996. /**
  997. * Sets an array on a uniform variable.
  998. * @param uniformName Name of the variable.
  999. * @param array array to be set.
  1000. * @returns this effect.
  1001. */
  1002. Effect.prototype.setArray = function (uniformName, array) {
  1003. this._valueCache[uniformName] = null;
  1004. this._engine.setArray(this.getUniform(uniformName), array);
  1005. return this;
  1006. };
  1007. /**
  1008. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1009. * @param uniformName Name of the variable.
  1010. * @param array array to be set.
  1011. * @returns this effect.
  1012. */
  1013. Effect.prototype.setArray2 = function (uniformName, array) {
  1014. this._valueCache[uniformName] = null;
  1015. this._engine.setArray2(this.getUniform(uniformName), array);
  1016. return this;
  1017. };
  1018. /**
  1019. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1020. * @param uniformName Name of the variable.
  1021. * @param array array to be set.
  1022. * @returns this effect.
  1023. */
  1024. Effect.prototype.setArray3 = function (uniformName, array) {
  1025. this._valueCache[uniformName] = null;
  1026. this._engine.setArray3(this.getUniform(uniformName), array);
  1027. return this;
  1028. };
  1029. /**
  1030. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1031. * @param uniformName Name of the variable.
  1032. * @param array array to be set.
  1033. * @returns this effect.
  1034. */
  1035. Effect.prototype.setArray4 = function (uniformName, array) {
  1036. this._valueCache[uniformName] = null;
  1037. this._engine.setArray4(this.getUniform(uniformName), array);
  1038. return this;
  1039. };
  1040. /**
  1041. * Sets matrices on a uniform variable.
  1042. * @param uniformName Name of the variable.
  1043. * @param matrices matrices to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1047. if (!matrices) {
  1048. return this;
  1049. }
  1050. this._valueCache[uniformName] = null;
  1051. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1052. return this;
  1053. };
  1054. /**
  1055. * Sets matrix on a uniform variable.
  1056. * @param uniformName Name of the variable.
  1057. * @param matrix matrix to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1061. if (this._cacheMatrix(uniformName, matrix)) {
  1062. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1063. }
  1064. return this;
  1065. };
  1066. /**
  1067. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1068. * @param uniformName Name of the variable.
  1069. * @param matrix matrix to be set.
  1070. * @returns this effect.
  1071. */
  1072. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1073. this._valueCache[uniformName] = null;
  1074. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1075. return this;
  1076. };
  1077. /**
  1078. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1079. * @param uniformName Name of the variable.
  1080. * @param matrix matrix to be set.
  1081. * @returns this effect.
  1082. */
  1083. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1084. this._valueCache[uniformName] = null;
  1085. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param value value to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setFloat = function (uniformName, value) {
  1095. var cache = this._valueCache[uniformName];
  1096. if (cache !== undefined && cache === value)
  1097. return this;
  1098. this._valueCache[uniformName] = value;
  1099. this._engine.setFloat(this.getUniform(uniformName), value);
  1100. return this;
  1101. };
  1102. /**
  1103. * Sets a boolean on a uniform variable.
  1104. * @param uniformName Name of the variable.
  1105. * @param bool value to be set.
  1106. * @returns this effect.
  1107. */
  1108. Effect.prototype.setBool = function (uniformName, bool) {
  1109. var cache = this._valueCache[uniformName];
  1110. if (cache !== undefined && cache === bool)
  1111. return this;
  1112. this._valueCache[uniformName] = bool;
  1113. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1114. return this;
  1115. };
  1116. /**
  1117. * Sets a Vector2 on a uniform variable.
  1118. * @param uniformName Name of the variable.
  1119. * @param vector2 vector2 to be set.
  1120. * @returns this effect.
  1121. */
  1122. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1123. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1124. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1125. }
  1126. return this;
  1127. };
  1128. /**
  1129. * Sets a float2 on a uniform variable.
  1130. * @param uniformName Name of the variable.
  1131. * @param x First float in float2.
  1132. * @param y Second float in float2.
  1133. * @returns this effect.
  1134. */
  1135. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1136. if (this._cacheFloat2(uniformName, x, y)) {
  1137. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1138. }
  1139. return this;
  1140. };
  1141. /**
  1142. * Sets a Vector3 on a uniform variable.
  1143. * @param uniformName Name of the variable.
  1144. * @param vector3 Value to be set.
  1145. * @returns this effect.
  1146. */
  1147. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1148. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1149. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1150. }
  1151. return this;
  1152. };
  1153. /**
  1154. * Sets a float3 on a uniform variable.
  1155. * @param uniformName Name of the variable.
  1156. * @param x First float in float3.
  1157. * @param y Second float in float3.
  1158. * @param z Third float in float3.
  1159. * @returns this effect.
  1160. */
  1161. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1162. if (this._cacheFloat3(uniformName, x, y, z)) {
  1163. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1164. }
  1165. return this;
  1166. };
  1167. /**
  1168. * Sets a Vector4 on a uniform variable.
  1169. * @param uniformName Name of the variable.
  1170. * @param vector4 Value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1174. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1175. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a float4 on a uniform variable.
  1181. * @param uniformName Name of the variable.
  1182. * @param x First float in float4.
  1183. * @param y Second float in float4.
  1184. * @param z Third float in float4.
  1185. * @param w Fourth float in float4.
  1186. * @returns this effect.
  1187. */
  1188. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1189. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1190. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1191. }
  1192. return this;
  1193. };
  1194. /**
  1195. * Sets a Color3 on a uniform variable.
  1196. * @param uniformName Name of the variable.
  1197. * @param color3 Value to be set.
  1198. * @returns this effect.
  1199. */
  1200. Effect.prototype.setColor3 = function (uniformName, color3) {
  1201. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1202. this._engine.setColor3(this.getUniform(uniformName), color3);
  1203. }
  1204. return this;
  1205. };
  1206. /**
  1207. * Sets a Color4 on a uniform variable.
  1208. * @param uniformName Name of the variable.
  1209. * @param color3 Value to be set.
  1210. * @param alpha Alpha value to be set.
  1211. * @returns this effect.
  1212. */
  1213. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1214. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1215. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1216. }
  1217. return this;
  1218. };
  1219. /**
  1220. * Sets a Color4 on a uniform variable
  1221. * @param uniformName defines the name of the variable
  1222. * @param color4 defines the value to be set
  1223. * @returns this effect.
  1224. */
  1225. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1226. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1227. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1228. }
  1229. return this;
  1230. };
  1231. /**
  1232. * Resets the cache of effects.
  1233. */
  1234. Effect.ResetCache = function () {
  1235. Effect._baseCache = {};
  1236. };
  1237. Effect._uniqueIdSeed = 0;
  1238. Effect._baseCache = {};
  1239. Effect._sourceCache = {};
  1240. // Statics
  1241. /**
  1242. * Store of each shader (The can be looked up using effect.key)
  1243. */
  1244. Effect.ShadersStore = {};
  1245. /**
  1246. * Store of each included file for a shader (The can be looked up using effect.key)
  1247. */
  1248. Effect.IncludesShadersStore = {};
  1249. return Effect;
  1250. }());
  1251. BABYLON.Effect = Effect;
  1252. })(BABYLON || (BABYLON = {}));
  1253. //# sourceMappingURL=babylon.effect.js.map
  1254. "use strict";
  1255. //# sourceMappingURL=babylon.types.js.map
  1256. "use strict";
  1257. var BABYLON;
  1258. (function (BABYLON) {
  1259. var KeyboardEventTypes = /** @class */ (function () {
  1260. function KeyboardEventTypes() {
  1261. }
  1262. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1263. get: function () {
  1264. return KeyboardEventTypes._KEYDOWN;
  1265. },
  1266. enumerable: true,
  1267. configurable: true
  1268. });
  1269. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1270. get: function () {
  1271. return KeyboardEventTypes._KEYUP;
  1272. },
  1273. enumerable: true,
  1274. configurable: true
  1275. });
  1276. KeyboardEventTypes._KEYDOWN = 0x01;
  1277. KeyboardEventTypes._KEYUP = 0x02;
  1278. return KeyboardEventTypes;
  1279. }());
  1280. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1281. var KeyboardInfo = /** @class */ (function () {
  1282. function KeyboardInfo(type, event) {
  1283. this.type = type;
  1284. this.event = event;
  1285. }
  1286. return KeyboardInfo;
  1287. }());
  1288. BABYLON.KeyboardInfo = KeyboardInfo;
  1289. /**
  1290. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1291. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1292. */
  1293. var KeyboardInfoPre = /** @class */ (function (_super) {
  1294. __extends(KeyboardInfoPre, _super);
  1295. function KeyboardInfoPre(type, event) {
  1296. var _this = _super.call(this, type, event) || this;
  1297. _this.skipOnPointerObservable = false;
  1298. return _this;
  1299. }
  1300. return KeyboardInfoPre;
  1301. }(KeyboardInfo));
  1302. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1303. })(BABYLON || (BABYLON = {}));
  1304. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1305. "use strict";
  1306. var BABYLON;
  1307. (function (BABYLON) {
  1308. var PointerEventTypes = /** @class */ (function () {
  1309. function PointerEventTypes() {
  1310. }
  1311. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1312. get: function () {
  1313. return PointerEventTypes._POINTERDOWN;
  1314. },
  1315. enumerable: true,
  1316. configurable: true
  1317. });
  1318. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1319. get: function () {
  1320. return PointerEventTypes._POINTERUP;
  1321. },
  1322. enumerable: true,
  1323. configurable: true
  1324. });
  1325. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1326. get: function () {
  1327. return PointerEventTypes._POINTERMOVE;
  1328. },
  1329. enumerable: true,
  1330. configurable: true
  1331. });
  1332. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1333. get: function () {
  1334. return PointerEventTypes._POINTERWHEEL;
  1335. },
  1336. enumerable: true,
  1337. configurable: true
  1338. });
  1339. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1340. get: function () {
  1341. return PointerEventTypes._POINTERPICK;
  1342. },
  1343. enumerable: true,
  1344. configurable: true
  1345. });
  1346. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1347. get: function () {
  1348. return PointerEventTypes._POINTERTAP;
  1349. },
  1350. enumerable: true,
  1351. configurable: true
  1352. });
  1353. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1354. get: function () {
  1355. return PointerEventTypes._POINTERDOUBLETAP;
  1356. },
  1357. enumerable: true,
  1358. configurable: true
  1359. });
  1360. PointerEventTypes._POINTERDOWN = 0x01;
  1361. PointerEventTypes._POINTERUP = 0x02;
  1362. PointerEventTypes._POINTERMOVE = 0x04;
  1363. PointerEventTypes._POINTERWHEEL = 0x08;
  1364. PointerEventTypes._POINTERPICK = 0x10;
  1365. PointerEventTypes._POINTERTAP = 0x20;
  1366. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1367. return PointerEventTypes;
  1368. }());
  1369. BABYLON.PointerEventTypes = PointerEventTypes;
  1370. var PointerInfoBase = /** @class */ (function () {
  1371. function PointerInfoBase(type, event) {
  1372. this.type = type;
  1373. this.event = event;
  1374. }
  1375. return PointerInfoBase;
  1376. }());
  1377. BABYLON.PointerInfoBase = PointerInfoBase;
  1378. /**
  1379. * This class is used to store pointer related info for the onPrePointerObservable event.
  1380. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1381. */
  1382. var PointerInfoPre = /** @class */ (function (_super) {
  1383. __extends(PointerInfoPre, _super);
  1384. function PointerInfoPre(type, event, localX, localY) {
  1385. var _this = _super.call(this, type, event) || this;
  1386. _this.skipOnPointerObservable = false;
  1387. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1388. return _this;
  1389. }
  1390. return PointerInfoPre;
  1391. }(PointerInfoBase));
  1392. BABYLON.PointerInfoPre = PointerInfoPre;
  1393. /**
  1394. * This type contains all the data related to a pointer event in Babylon.js.
  1395. * 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.
  1396. */
  1397. var PointerInfo = /** @class */ (function (_super) {
  1398. __extends(PointerInfo, _super);
  1399. function PointerInfo(type, event, pickInfo) {
  1400. var _this = _super.call(this, type, event) || this;
  1401. _this.pickInfo = pickInfo;
  1402. return _this;
  1403. }
  1404. return PointerInfo;
  1405. }(PointerInfoBase));
  1406. BABYLON.PointerInfo = PointerInfo;
  1407. })(BABYLON || (BABYLON = {}));
  1408. //# sourceMappingURL=babylon.pointerEvents.js.map
  1409. "use strict";
  1410. var BABYLON;
  1411. (function (BABYLON) {
  1412. BABYLON.ToGammaSpace = 1 / 2.2;
  1413. BABYLON.ToLinearSpace = 2.2;
  1414. BABYLON.Epsilon = 0.001;
  1415. /**
  1416. * Class used to hold a RBG color
  1417. */
  1418. var Color3 = /** @class */ (function () {
  1419. /**
  1420. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1421. * @param r defines the red component (between 0 and 1, default is 0)
  1422. * @param g defines the green component (between 0 and 1, default is 0)
  1423. * @param b defines the blue component (between 0 and 1, default is 0)
  1424. */
  1425. function Color3(
  1426. /**
  1427. * Defines the red component (between 0 and 1, default is 0)
  1428. */
  1429. r,
  1430. /**
  1431. * Defines the green component (between 0 and 1, default is 0)
  1432. */
  1433. g,
  1434. /**
  1435. * Defines the blue component (between 0 and 1, default is 0)
  1436. */
  1437. b) {
  1438. if (r === void 0) { r = 0; }
  1439. if (g === void 0) { g = 0; }
  1440. if (b === void 0) { b = 0; }
  1441. this.r = r;
  1442. this.g = g;
  1443. this.b = b;
  1444. }
  1445. /**
  1446. * Creates a string with the Color3 current values
  1447. * @returns the string representation of the Color3 object
  1448. */
  1449. Color3.prototype.toString = function () {
  1450. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1451. };
  1452. /**
  1453. * Returns the string "Color3"
  1454. * @returns "Color3"
  1455. */
  1456. Color3.prototype.getClassName = function () {
  1457. return "Color3";
  1458. };
  1459. /**
  1460. * Compute the Color3 hash code
  1461. * @returns an unique number that can be used to hash Color3 objects
  1462. */
  1463. Color3.prototype.getHashCode = function () {
  1464. var hash = this.r || 0;
  1465. hash = (hash * 397) ^ (this.g || 0);
  1466. hash = (hash * 397) ^ (this.b || 0);
  1467. return hash;
  1468. };
  1469. // Operators
  1470. /**
  1471. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1472. * @param array defines the array where to store the r,g,b components
  1473. * @param index defines an optional index in the target array to define where to start storing values
  1474. * @returns the current Color3 object
  1475. */
  1476. Color3.prototype.toArray = function (array, index) {
  1477. if (index === undefined) {
  1478. index = 0;
  1479. }
  1480. array[index] = this.r;
  1481. array[index + 1] = this.g;
  1482. array[index + 2] = this.b;
  1483. return this;
  1484. };
  1485. /**
  1486. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1487. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1488. * @returns a new {BABYLON.Color4} object
  1489. */
  1490. Color3.prototype.toColor4 = function (alpha) {
  1491. if (alpha === void 0) { alpha = 1; }
  1492. return new Color4(this.r, this.g, this.b, alpha);
  1493. };
  1494. /**
  1495. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1496. * @returns the new array
  1497. */
  1498. Color3.prototype.asArray = function () {
  1499. var result = new Array();
  1500. this.toArray(result, 0);
  1501. return result;
  1502. };
  1503. /**
  1504. * Returns the luminance value
  1505. * @returns a float value
  1506. */
  1507. Color3.prototype.toLuminance = function () {
  1508. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1509. };
  1510. /**
  1511. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1512. * @param otherColor defines the second operand
  1513. * @returns the new Color3 object
  1514. */
  1515. Color3.prototype.multiply = function (otherColor) {
  1516. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1517. };
  1518. /**
  1519. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1520. * @param otherColor defines the second operand
  1521. * @param result defines the Color3 object where to store the result
  1522. * @returns the current Color3
  1523. */
  1524. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1525. result.r = this.r * otherColor.r;
  1526. result.g = this.g * otherColor.g;
  1527. result.b = this.b * otherColor.b;
  1528. return this;
  1529. };
  1530. /**
  1531. * Determines equality between Color3 objects
  1532. * @param otherColor defines the second operand
  1533. * @returns true if the rgb values are equal to the passed ones
  1534. */
  1535. Color3.prototype.equals = function (otherColor) {
  1536. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1537. };
  1538. /**
  1539. * Determines equality between the current Color3 object and a set of r,b,g values
  1540. * @param r defines the red component to check
  1541. * @param g defines the green component to check
  1542. * @param b defines the blue component to check
  1543. * @returns true if the rgb values are equal to the passed ones
  1544. */
  1545. Color3.prototype.equalsFloats = function (r, g, b) {
  1546. return this.r === r && this.g === g && this.b === b;
  1547. };
  1548. /**
  1549. * Multiplies in place each rgb value by scale
  1550. * @param scale defines the scaling factor
  1551. * @returns the updated Color3
  1552. */
  1553. Color3.prototype.scale = function (scale) {
  1554. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1555. };
  1556. /**
  1557. * Multiplies the rgb values by scale and stores the result into "result"
  1558. * @param scale defines the scaling factor
  1559. * @param result defines the Color3 object where to store the result
  1560. * @returns the unmodified current Color3
  1561. */
  1562. Color3.prototype.scaleToRef = function (scale, result) {
  1563. result.r = this.r * scale;
  1564. result.g = this.g * scale;
  1565. result.b = this.b * scale;
  1566. return this;
  1567. };
  1568. /**
  1569. * Scale the current Color3 values by a factor and add the result to a given Color3
  1570. * @param scale defines the scale factor
  1571. * @param result defines color to store the result into
  1572. * @returns the unmodified current Color3
  1573. */
  1574. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1575. result.r += this.r * scale;
  1576. result.g += this.g * scale;
  1577. result.b += this.b * scale;
  1578. return this;
  1579. };
  1580. /**
  1581. * Clamps the rgb values by the min and max values and stores the result into "result"
  1582. * @param min defines minimum clamping value (default is 0)
  1583. * @param max defines maximum clamping value (default is 1)
  1584. * @param result defines color to store the result into
  1585. * @returns the original Color3
  1586. */
  1587. Color3.prototype.clampToRef = function (min, max, result) {
  1588. if (min === void 0) { min = 0; }
  1589. if (max === void 0) { max = 1; }
  1590. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1591. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1592. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1593. return this;
  1594. };
  1595. /**
  1596. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1597. * @param otherColor defines the second operand
  1598. * @returns the new Color3
  1599. */
  1600. Color3.prototype.add = function (otherColor) {
  1601. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1602. };
  1603. /**
  1604. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1605. * @param otherColor defines the second operand
  1606. * @param result defines Color3 object to store the result into
  1607. * @returns the unmodified current Color3
  1608. */
  1609. Color3.prototype.addToRef = function (otherColor, result) {
  1610. result.r = this.r + otherColor.r;
  1611. result.g = this.g + otherColor.g;
  1612. result.b = this.b + otherColor.b;
  1613. return this;
  1614. };
  1615. /**
  1616. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1617. * @param otherColor defines the second operand
  1618. * @returns the new Color3
  1619. */
  1620. Color3.prototype.subtract = function (otherColor) {
  1621. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1622. };
  1623. /**
  1624. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1625. * @param otherColor defines the second operand
  1626. * @param result defines Color3 object to store the result into
  1627. * @returns the unmodified current Color3
  1628. */
  1629. Color3.prototype.subtractToRef = function (otherColor, result) {
  1630. result.r = this.r - otherColor.r;
  1631. result.g = this.g - otherColor.g;
  1632. result.b = this.b - otherColor.b;
  1633. return this;
  1634. };
  1635. /**
  1636. * Copy the current object
  1637. * @returns a new Color3 copied the current one
  1638. */
  1639. Color3.prototype.clone = function () {
  1640. return new Color3(this.r, this.g, this.b);
  1641. };
  1642. /**
  1643. * Copies the rgb values from the source in the current Color3
  1644. * @param source defines the source Color3 object
  1645. * @returns the updated Color3 object
  1646. */
  1647. Color3.prototype.copyFrom = function (source) {
  1648. this.r = source.r;
  1649. this.g = source.g;
  1650. this.b = source.b;
  1651. return this;
  1652. };
  1653. /**
  1654. * Updates the Color3 rgb values from the passed floats
  1655. * @param r defines the red component to read from
  1656. * @param g defines the green component to read from
  1657. * @param b defines the blue component to read from
  1658. * @returns the current Color3 object
  1659. */
  1660. Color3.prototype.copyFromFloats = function (r, g, b) {
  1661. this.r = r;
  1662. this.g = g;
  1663. this.b = b;
  1664. return this;
  1665. };
  1666. /**
  1667. * Updates the Color3 rgb values from the passed floats
  1668. * @param r defines the red component to read from
  1669. * @param g defines the green component to read from
  1670. * @param b defines the blue component to read from
  1671. * @returns the current Color3 object
  1672. */
  1673. Color3.prototype.set = function (r, g, b) {
  1674. return this.copyFromFloats(r, g, b);
  1675. };
  1676. /**
  1677. * Compute the Color3 hexadecimal code as a string
  1678. * @returns a string containing the hexadecimal representation of the Color3 object
  1679. */
  1680. Color3.prototype.toHexString = function () {
  1681. var intR = (this.r * 255) | 0;
  1682. var intG = (this.g * 255) | 0;
  1683. var intB = (this.b * 255) | 0;
  1684. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1685. };
  1686. /**
  1687. * Computes a new Color3 converted from the current one to linear space
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.prototype.toLinearSpace = function () {
  1691. var convertedColor = new Color3();
  1692. this.toLinearSpaceToRef(convertedColor);
  1693. return convertedColor;
  1694. };
  1695. /**
  1696. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1697. * @param convertedColor defines the Color3 object where to store the linear space version
  1698. * @returns the unmodified Color3
  1699. */
  1700. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1701. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1702. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1703. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1704. return this;
  1705. };
  1706. /**
  1707. * Computes a new Color3 converted from the current one to gamma space
  1708. * @returns a new Color3 object
  1709. */
  1710. Color3.prototype.toGammaSpace = function () {
  1711. var convertedColor = new Color3();
  1712. this.toGammaSpaceToRef(convertedColor);
  1713. return convertedColor;
  1714. };
  1715. /**
  1716. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1717. * @param convertedColor defines the Color3 object where to store the gamma space version
  1718. * @returns the unmodified Color3
  1719. */
  1720. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1721. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1722. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1723. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1724. return this;
  1725. };
  1726. // Statics
  1727. /**
  1728. * Creates a new Color3 from the string containing valid hexadecimal values
  1729. * @param hex defines a string containing valid hexadecimal values
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.FromHexString = function (hex) {
  1733. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1734. return new Color3(0, 0, 0);
  1735. }
  1736. var r = parseInt(hex.substring(1, 3), 16);
  1737. var g = parseInt(hex.substring(3, 5), 16);
  1738. var b = parseInt(hex.substring(5, 7), 16);
  1739. return Color3.FromInts(r, g, b);
  1740. };
  1741. /**
  1742. * Creates a new Vector3 from the starting index of the passed array
  1743. * @param array defines the source array
  1744. * @param offset defines an offset in the source array
  1745. * @returns a new Color3 object
  1746. */
  1747. Color3.FromArray = function (array, offset) {
  1748. if (offset === void 0) { offset = 0; }
  1749. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1750. };
  1751. /**
  1752. * Creates a new Color3 from integer values (< 256)
  1753. * @param r defines the red component to read from (value between 0 and 255)
  1754. * @param g defines the green component to read from (value between 0 and 255)
  1755. * @param b defines the blue component to read from (value between 0 and 255)
  1756. * @returns a new Color3 object
  1757. */
  1758. Color3.FromInts = function (r, g, b) {
  1759. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1760. };
  1761. /**
  1762. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1763. * @param start defines the start Color3 value
  1764. * @param end defines the end Color3 value
  1765. * @param amount defines the gradient value between start and end
  1766. * @returns a new Color3 object
  1767. */
  1768. Color3.Lerp = function (start, end, amount) {
  1769. var r = start.r + ((end.r - start.r) * amount);
  1770. var g = start.g + ((end.g - start.g) * amount);
  1771. var b = start.b + ((end.b - start.b) * amount);
  1772. return new Color3(r, g, b);
  1773. };
  1774. /**
  1775. * Returns a Color3 value containing a red color
  1776. * @returns a new Color3 object
  1777. */
  1778. Color3.Red = function () { return new Color3(1, 0, 0); };
  1779. /**
  1780. * Returns a Color3 value containing a green color
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.Green = function () { return new Color3(0, 1, 0); };
  1784. /**
  1785. * Returns a Color3 value containing a blue color
  1786. * @returns a new Color3 object
  1787. */
  1788. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1789. /**
  1790. * Returns a Color3 value containing a black color
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.Black = function () { return new Color3(0, 0, 0); };
  1794. /**
  1795. * Returns a Color3 value containing a white color
  1796. * @returns a new Color3 object
  1797. */
  1798. Color3.White = function () { return new Color3(1, 1, 1); };
  1799. /**
  1800. * Returns a Color3 value containing a purple color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1804. /**
  1805. * Returns a Color3 value containing a magenta color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1809. /**
  1810. * Returns a Color3 value containing a yellow color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1814. /**
  1815. * Returns a Color3 value containing a gray color
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1819. /**
  1820. * Returns a Color3 value containing a teal color
  1821. * @returns a new Color3 object
  1822. */
  1823. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1824. /**
  1825. * Returns a Color3 value containing a random color
  1826. * @returns a new Color3 object
  1827. */
  1828. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1829. return Color3;
  1830. }());
  1831. BABYLON.Color3 = Color3;
  1832. /**
  1833. * Class used to hold a RBGA color
  1834. */
  1835. var Color4 = /** @class */ (function () {
  1836. /**
  1837. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1838. * @param r defines the red component (between 0 and 1, default is 0)
  1839. * @param g defines the green component (between 0 and 1, default is 0)
  1840. * @param b defines the blue component (between 0 and 1, default is 0)
  1841. * @param a defines the alpha component (between 0 and 1, default is 1)
  1842. */
  1843. function Color4(
  1844. /**
  1845. * Defines the red component (between 0 and 1, default is 0)
  1846. */
  1847. r,
  1848. /**
  1849. * Defines the green component (between 0 and 1, default is 0)
  1850. */
  1851. g,
  1852. /**
  1853. * Defines the blue component (between 0 and 1, default is 0)
  1854. */
  1855. b,
  1856. /**
  1857. * Defines the alpha component (between 0 and 1, default is 1)
  1858. */
  1859. a) {
  1860. if (r === void 0) { r = 0; }
  1861. if (g === void 0) { g = 0; }
  1862. if (b === void 0) { b = 0; }
  1863. if (a === void 0) { a = 1; }
  1864. this.r = r;
  1865. this.g = g;
  1866. this.b = b;
  1867. this.a = a;
  1868. }
  1869. // Operators
  1870. /**
  1871. * Adds in place the passed Color4 values to the current Color4 object
  1872. * @param right defines the second operand
  1873. * @returns the current updated Color4 object
  1874. */
  1875. Color4.prototype.addInPlace = function (right) {
  1876. this.r += right.r;
  1877. this.g += right.g;
  1878. this.b += right.b;
  1879. this.a += right.a;
  1880. return this;
  1881. };
  1882. /**
  1883. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1884. * @returns the new array
  1885. */
  1886. Color4.prototype.asArray = function () {
  1887. var result = new Array();
  1888. this.toArray(result, 0);
  1889. return result;
  1890. };
  1891. /**
  1892. * Stores from the starting index in the passed array the Color4 successive values
  1893. * @param array defines the array where to store the r,g,b components
  1894. * @param index defines an optional index in the target array to define where to start storing values
  1895. * @returns the current Color4 object
  1896. */
  1897. Color4.prototype.toArray = function (array, index) {
  1898. if (index === undefined) {
  1899. index = 0;
  1900. }
  1901. array[index] = this.r;
  1902. array[index + 1] = this.g;
  1903. array[index + 2] = this.b;
  1904. array[index + 3] = this.a;
  1905. return this;
  1906. };
  1907. /**
  1908. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1909. * @param right defines the second operand
  1910. * @returns a new Color4 object
  1911. */
  1912. Color4.prototype.add = function (right) {
  1913. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1914. };
  1915. /**
  1916. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1917. * @param right defines the second operand
  1918. * @returns a new Color4 object
  1919. */
  1920. Color4.prototype.subtract = function (right) {
  1921. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1922. };
  1923. /**
  1924. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1925. * @param right defines the second operand
  1926. * @param result defines the Color4 object where to store the result
  1927. * @returns the current Color4 object
  1928. */
  1929. Color4.prototype.subtractToRef = function (right, result) {
  1930. result.r = this.r - right.r;
  1931. result.g = this.g - right.g;
  1932. result.b = this.b - right.b;
  1933. result.a = this.a - right.a;
  1934. return this;
  1935. };
  1936. /**
  1937. * Creates a new Color4 with the current Color4 values multiplied by scale
  1938. * @param scale defines the scaling factor to apply
  1939. * @returns a new Color4 object
  1940. */
  1941. Color4.prototype.scale = function (scale) {
  1942. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1943. };
  1944. /**
  1945. * Multiplies the current Color4 values by scale and stores the result in "result"
  1946. * @param scale defines the scaling factor to apply
  1947. * @param result defines the Color4 object where to store the result
  1948. * @returns the current unmodified Color4
  1949. */
  1950. Color4.prototype.scaleToRef = function (scale, result) {
  1951. result.r = this.r * scale;
  1952. result.g = this.g * scale;
  1953. result.b = this.b * scale;
  1954. result.a = this.a * scale;
  1955. return this;
  1956. };
  1957. /**
  1958. * Scale the current Color4 values by a factor and add the result to a given Color4
  1959. * @param scale defines the scale factor
  1960. * @param result defines the Color4 object where to store the result
  1961. * @returns the unmodified current Color4
  1962. */
  1963. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1964. result.r += this.r * scale;
  1965. result.g += this.g * scale;
  1966. result.b += this.b * scale;
  1967. result.a += this.a * scale;
  1968. return this;
  1969. };
  1970. /**
  1971. * Clamps the rgb values by the min and max values and stores the result into "result"
  1972. * @param min defines minimum clamping value (default is 0)
  1973. * @param max defines maximum clamping value (default is 1)
  1974. * @param result defines color to store the result into.
  1975. * @returns the cuurent Color4
  1976. */
  1977. Color4.prototype.clampToRef = function (min, max, result) {
  1978. if (min === void 0) { min = 0; }
  1979. if (max === void 0) { max = 1; }
  1980. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1981. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1982. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1983. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1984. return this;
  1985. };
  1986. /**
  1987. * Multipy an Color4 value by another and return a new Color4 object
  1988. * @param color defines the Color4 value to multiply by
  1989. * @returns a new Color4 object
  1990. */
  1991. Color4.prototype.multiply = function (color) {
  1992. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1993. };
  1994. /**
  1995. * Multipy a Color4 value by another and push the result in a reference value
  1996. * @param color defines the Color4 value to multiply by
  1997. * @param result defines the Color4 to fill the result in
  1998. * @returns the result Color4
  1999. */
  2000. Color4.prototype.multiplyToRef = function (color, result) {
  2001. result.r = this.r * color.r;
  2002. result.g = this.g * color.g;
  2003. result.b = this.b * color.b;
  2004. result.a = this.a * color.a;
  2005. return result;
  2006. };
  2007. /**
  2008. * Creates a string with the Color4 current values
  2009. * @returns the string representation of the Color4 object
  2010. */
  2011. Color4.prototype.toString = function () {
  2012. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2013. };
  2014. /**
  2015. * Returns the string "Color4"
  2016. * @returns "Color4"
  2017. */
  2018. Color4.prototype.getClassName = function () {
  2019. return "Color4";
  2020. };
  2021. /**
  2022. * Compute the Color4 hash code
  2023. * @returns an unique number that can be used to hash Color4 objects
  2024. */
  2025. Color4.prototype.getHashCode = function () {
  2026. var hash = this.r || 0;
  2027. hash = (hash * 397) ^ (this.g || 0);
  2028. hash = (hash * 397) ^ (this.b || 0);
  2029. hash = (hash * 397) ^ (this.a || 0);
  2030. return hash;
  2031. };
  2032. /**
  2033. * Creates a new Color4 copied from the current one
  2034. * @returns a new Color4 object
  2035. */
  2036. Color4.prototype.clone = function () {
  2037. return new Color4(this.r, this.g, this.b, this.a);
  2038. };
  2039. /**
  2040. * Copies the passed Color4 values into the current one
  2041. * @param source defines the source Color4 object
  2042. * @returns the current updated Color4 object
  2043. */
  2044. Color4.prototype.copyFrom = function (source) {
  2045. this.r = source.r;
  2046. this.g = source.g;
  2047. this.b = source.b;
  2048. this.a = source.a;
  2049. return this;
  2050. };
  2051. /**
  2052. * Copies the passed float values into the current one
  2053. * @param r defines the red component to read from
  2054. * @param g defines the green component to read from
  2055. * @param b defines the blue component to read from
  2056. * @param a defines the alpha component to read from
  2057. * @returns the current updated Color4 object
  2058. */
  2059. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2060. this.r = r;
  2061. this.g = g;
  2062. this.b = b;
  2063. this.a = a;
  2064. return this;
  2065. };
  2066. /**
  2067. * Copies the passed float values into the current one
  2068. * @param r defines the red component to read from
  2069. * @param g defines the green component to read from
  2070. * @param b defines the blue component to read from
  2071. * @param a defines the alpha component to read from
  2072. * @returns the current updated Color4 object
  2073. */
  2074. Color4.prototype.set = function (r, g, b, a) {
  2075. return this.copyFromFloats(r, g, b, a);
  2076. };
  2077. /**
  2078. * Compute the Color4 hexadecimal code as a string
  2079. * @returns a string containing the hexadecimal representation of the Color4 object
  2080. */
  2081. Color4.prototype.toHexString = function () {
  2082. var intR = (this.r * 255) | 0;
  2083. var intG = (this.g * 255) | 0;
  2084. var intB = (this.b * 255) | 0;
  2085. var intA = (this.a * 255) | 0;
  2086. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2087. };
  2088. /**
  2089. * Computes a new Color4 converted from the current one to linear space
  2090. * @returns a new Color4 object
  2091. */
  2092. Color4.prototype.toLinearSpace = function () {
  2093. var convertedColor = new Color4();
  2094. this.toLinearSpaceToRef(convertedColor);
  2095. return convertedColor;
  2096. };
  2097. /**
  2098. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2099. * @param convertedColor defines the Color4 object where to store the linear space version
  2100. * @returns the unmodified Color4
  2101. */
  2102. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2103. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2104. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2105. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2106. convertedColor.a = this.a;
  2107. return this;
  2108. };
  2109. /**
  2110. * Computes a new Color4 converted from the current one to gamma space
  2111. * @returns a new Color4 object
  2112. */
  2113. Color4.prototype.toGammaSpace = function () {
  2114. var convertedColor = new Color4();
  2115. this.toGammaSpaceToRef(convertedColor);
  2116. return convertedColor;
  2117. };
  2118. /**
  2119. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2120. * @param convertedColor defines the Color4 object where to store the gamma space version
  2121. * @returns the unmodified Color4
  2122. */
  2123. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2124. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2125. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2126. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2127. convertedColor.a = this.a;
  2128. return this;
  2129. };
  2130. // Statics
  2131. /**
  2132. * Creates a new Color4 from the string containing valid hexadecimal values
  2133. * @param hex defines a string containing valid hexadecimal values
  2134. * @returns a new Color4 object
  2135. */
  2136. Color4.FromHexString = function (hex) {
  2137. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2138. return new Color4(0.0, 0.0, 0.0, 0.0);
  2139. }
  2140. var r = parseInt(hex.substring(1, 3), 16);
  2141. var g = parseInt(hex.substring(3, 5), 16);
  2142. var b = parseInt(hex.substring(5, 7), 16);
  2143. var a = parseInt(hex.substring(7, 9), 16);
  2144. return Color4.FromInts(r, g, b, a);
  2145. };
  2146. /**
  2147. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2148. * @param left defines the start value
  2149. * @param right defines the end value
  2150. * @param amount defines the gradient factor
  2151. * @returns a new Color4 object
  2152. */
  2153. Color4.Lerp = function (left, right, amount) {
  2154. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2155. Color4.LerpToRef(left, right, amount, result);
  2156. return result;
  2157. };
  2158. /**
  2159. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2160. * @param left defines the start value
  2161. * @param right defines the end value
  2162. * @param amount defines the gradient factor
  2163. * @param result defines the Color4 object where to store data
  2164. */
  2165. Color4.LerpToRef = function (left, right, amount, result) {
  2166. result.r = left.r + (right.r - left.r) * amount;
  2167. result.g = left.g + (right.g - left.g) * amount;
  2168. result.b = left.b + (right.b - left.b) * amount;
  2169. result.a = left.a + (right.a - left.a) * amount;
  2170. };
  2171. /**
  2172. * Creates a new Color4 from the starting index element of the passed array
  2173. * @param array defines the source array to read from
  2174. * @param offset defines the offset in the source array
  2175. * @returns a new Color4 object
  2176. */
  2177. Color4.FromArray = function (array, offset) {
  2178. if (offset === void 0) { offset = 0; }
  2179. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2180. };
  2181. /**
  2182. * Creates a new Color3 from integer values (< 256)
  2183. * @param r defines the red component to read from (value between 0 and 255)
  2184. * @param g defines the green component to read from (value between 0 and 255)
  2185. * @param b defines the blue component to read from (value between 0 and 255)
  2186. * @param a defines the alpha component to read from (value between 0 and 255)
  2187. * @returns a new Color3 object
  2188. */
  2189. Color4.FromInts = function (r, g, b, a) {
  2190. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2191. };
  2192. /**
  2193. * Check the content of a given array and convert it to an array containing RGBA data
  2194. * If the original array was already containing count * 4 values then it is returned directly
  2195. * @param colors defines the array to check
  2196. * @param count defines the number of RGBA data to expect
  2197. * @returns an array containing count * 4 values (RGBA)
  2198. */
  2199. Color4.CheckColors4 = function (colors, count) {
  2200. // Check if color3 was used
  2201. if (colors.length === count * 3) {
  2202. var colors4 = [];
  2203. for (var index = 0; index < colors.length; index += 3) {
  2204. var newIndex = (index / 3) * 4;
  2205. colors4[newIndex] = colors[index];
  2206. colors4[newIndex + 1] = colors[index + 1];
  2207. colors4[newIndex + 2] = colors[index + 2];
  2208. colors4[newIndex + 3] = 1.0;
  2209. }
  2210. return colors4;
  2211. }
  2212. return colors;
  2213. };
  2214. return Color4;
  2215. }());
  2216. BABYLON.Color4 = Color4;
  2217. var Vector2 = /** @class */ (function () {
  2218. /**
  2219. * Creates a new Vector2 from the passed x and y coordinates.
  2220. */
  2221. function Vector2(x, y) {
  2222. this.x = x;
  2223. this.y = y;
  2224. }
  2225. /**
  2226. * Returns a string with the Vector2 coordinates.
  2227. */
  2228. Vector2.prototype.toString = function () {
  2229. return "{X: " + this.x + " Y:" + this.y + "}";
  2230. };
  2231. /**
  2232. * Returns the string "Vector2"
  2233. */
  2234. Vector2.prototype.getClassName = function () {
  2235. return "Vector2";
  2236. };
  2237. /**
  2238. * Returns the Vector2 hash code as a number.
  2239. */
  2240. Vector2.prototype.getHashCode = function () {
  2241. var hash = this.x || 0;
  2242. hash = (hash * 397) ^ (this.y || 0);
  2243. return hash;
  2244. };
  2245. // Operators
  2246. /**
  2247. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2248. * Returns the Vector2.
  2249. */
  2250. Vector2.prototype.toArray = function (array, index) {
  2251. if (index === void 0) { index = 0; }
  2252. array[index] = this.x;
  2253. array[index + 1] = this.y;
  2254. return this;
  2255. };
  2256. /**
  2257. * Returns a new array with 2 elements : the Vector2 coordinates.
  2258. */
  2259. Vector2.prototype.asArray = function () {
  2260. var result = new Array();
  2261. this.toArray(result, 0);
  2262. return result;
  2263. };
  2264. /**
  2265. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2266. * Returns the updated Vector2.
  2267. */
  2268. Vector2.prototype.copyFrom = function (source) {
  2269. this.x = source.x;
  2270. this.y = source.y;
  2271. return this;
  2272. };
  2273. /**
  2274. * Sets the Vector2 coordinates with the passed floats.
  2275. * Returns the updated Vector2.
  2276. */
  2277. Vector2.prototype.copyFromFloats = function (x, y) {
  2278. this.x = x;
  2279. this.y = y;
  2280. return this;
  2281. };
  2282. /**
  2283. * Sets the Vector2 coordinates with the passed floats.
  2284. * Returns the updated Vector2.
  2285. */
  2286. Vector2.prototype.set = function (x, y) {
  2287. return this.copyFromFloats(x, y);
  2288. };
  2289. /**
  2290. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2291. */
  2292. Vector2.prototype.add = function (otherVector) {
  2293. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2294. };
  2295. /**
  2296. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2297. * Returns the Vector2.
  2298. */
  2299. Vector2.prototype.addToRef = function (otherVector, result) {
  2300. result.x = this.x + otherVector.x;
  2301. result.y = this.y + otherVector.y;
  2302. return this;
  2303. };
  2304. /**
  2305. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2306. * Returns the updated Vector2.
  2307. */
  2308. Vector2.prototype.addInPlace = function (otherVector) {
  2309. this.x += otherVector.x;
  2310. this.y += otherVector.y;
  2311. return this;
  2312. };
  2313. /**
  2314. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2315. */
  2316. Vector2.prototype.addVector3 = function (otherVector) {
  2317. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2318. };
  2319. /**
  2320. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2321. */
  2322. Vector2.prototype.subtract = function (otherVector) {
  2323. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2324. };
  2325. /**
  2326. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2327. * Returns the Vector2.
  2328. */
  2329. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2330. result.x = this.x - otherVector.x;
  2331. result.y = this.y - otherVector.y;
  2332. return this;
  2333. };
  2334. /**
  2335. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2336. * Returns the updated Vector2.
  2337. */
  2338. Vector2.prototype.subtractInPlace = function (otherVector) {
  2339. this.x -= otherVector.x;
  2340. this.y -= otherVector.y;
  2341. return this;
  2342. };
  2343. /**
  2344. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2345. * Returns the updated Vector2.
  2346. */
  2347. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2348. this.x *= otherVector.x;
  2349. this.y *= otherVector.y;
  2350. return this;
  2351. };
  2352. /**
  2353. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2354. */
  2355. Vector2.prototype.multiply = function (otherVector) {
  2356. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2357. };
  2358. /**
  2359. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2360. * Returns the Vector2.
  2361. */
  2362. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2363. result.x = this.x * otherVector.x;
  2364. result.y = this.y * otherVector.y;
  2365. return this;
  2366. };
  2367. /**
  2368. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2369. */
  2370. Vector2.prototype.multiplyByFloats = function (x, y) {
  2371. return new Vector2(this.x * x, this.y * y);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2375. */
  2376. Vector2.prototype.divide = function (otherVector) {
  2377. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2378. };
  2379. /**
  2380. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2381. * Returns the Vector2.
  2382. */
  2383. Vector2.prototype.divideToRef = function (otherVector, result) {
  2384. result.x = this.x / otherVector.x;
  2385. result.y = this.y / otherVector.y;
  2386. return this;
  2387. };
  2388. /**
  2389. * Divides the current Vector3 coordinates by the passed ones.
  2390. * Returns the updated Vector3.
  2391. */
  2392. Vector2.prototype.divideInPlace = function (otherVector) {
  2393. return this.divideToRef(otherVector, this);
  2394. };
  2395. /**
  2396. * Returns a new Vector2 with current Vector2 negated coordinates.
  2397. */
  2398. Vector2.prototype.negate = function () {
  2399. return new Vector2(-this.x, -this.y);
  2400. };
  2401. /**
  2402. * Multiply the Vector2 coordinates by scale.
  2403. * Returns the updated Vector2.
  2404. */
  2405. Vector2.prototype.scaleInPlace = function (scale) {
  2406. this.x *= scale;
  2407. this.y *= scale;
  2408. return this;
  2409. };
  2410. /**
  2411. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2412. */
  2413. Vector2.prototype.scale = function (scale) {
  2414. var result = new Vector2(0, 0);
  2415. this.scaleToRef(scale, result);
  2416. return result;
  2417. };
  2418. /**
  2419. * Scale the current Vector2 values by a factor to a given Vector2
  2420. * @param scale defines the scale factor
  2421. * @param result defines the Vector2 object where to store the result
  2422. * @returns the unmodified current Vector2
  2423. */
  2424. Vector2.prototype.scaleToRef = function (scale, result) {
  2425. result.x = this.x * scale;
  2426. result.y = this.y * scale;
  2427. return this;
  2428. };
  2429. /**
  2430. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2431. * @param scale defines the scale factor
  2432. * @param result defines the Vector2 object where to store the result
  2433. * @returns the unmodified current Vector2
  2434. */
  2435. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2436. result.x += this.x * scale;
  2437. result.y += this.y * scale;
  2438. return this;
  2439. };
  2440. /**
  2441. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2442. */
  2443. Vector2.prototype.equals = function (otherVector) {
  2444. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2445. };
  2446. /**
  2447. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2448. */
  2449. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2450. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2451. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2452. };
  2453. // Properties
  2454. /**
  2455. * Returns the vector length (float).
  2456. */
  2457. Vector2.prototype.length = function () {
  2458. return Math.sqrt(this.x * this.x + this.y * this.y);
  2459. };
  2460. /**
  2461. * Returns the vector squared length (float);
  2462. */
  2463. Vector2.prototype.lengthSquared = function () {
  2464. return (this.x * this.x + this.y * this.y);
  2465. };
  2466. // Methods
  2467. /**
  2468. * Normalize the vector.
  2469. * Returns the updated Vector2.
  2470. */
  2471. Vector2.prototype.normalize = function () {
  2472. var len = this.length();
  2473. if (len === 0)
  2474. return this;
  2475. var num = 1.0 / len;
  2476. this.x *= num;
  2477. this.y *= num;
  2478. return this;
  2479. };
  2480. /**
  2481. * Returns a new Vector2 copied from the Vector2.
  2482. */
  2483. Vector2.prototype.clone = function () {
  2484. return new Vector2(this.x, this.y);
  2485. };
  2486. // Statics
  2487. /**
  2488. * Returns a new Vector2(0, 0)
  2489. */
  2490. Vector2.Zero = function () {
  2491. return new Vector2(0, 0);
  2492. };
  2493. /**
  2494. * Returns a new Vector2(1, 1)
  2495. */
  2496. Vector2.One = function () {
  2497. return new Vector2(1, 1);
  2498. };
  2499. /**
  2500. * Returns a new Vector2 set from the passed index element of the passed array.
  2501. */
  2502. Vector2.FromArray = function (array, offset) {
  2503. if (offset === void 0) { offset = 0; }
  2504. return new Vector2(array[offset], array[offset + 1]);
  2505. };
  2506. /**
  2507. * Sets "result" from the passed index element of the passed array.
  2508. */
  2509. Vector2.FromArrayToRef = function (array, offset, result) {
  2510. result.x = array[offset];
  2511. result.y = array[offset + 1];
  2512. };
  2513. /**
  2514. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2515. */
  2516. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2517. var squared = amount * amount;
  2518. var cubed = amount * squared;
  2519. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2520. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2521. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2522. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2523. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2524. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2525. return new Vector2(x, y);
  2526. };
  2527. /**
  2528. * 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".
  2529. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2530. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2531. */
  2532. Vector2.Clamp = function (value, min, max) {
  2533. var x = value.x;
  2534. x = (x > max.x) ? max.x : x;
  2535. x = (x < min.x) ? min.x : x;
  2536. var y = value.y;
  2537. y = (y > max.y) ? max.y : y;
  2538. y = (y < min.y) ? min.y : y;
  2539. return new Vector2(x, y);
  2540. };
  2541. /**
  2542. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2543. */
  2544. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2545. var squared = amount * amount;
  2546. var cubed = amount * squared;
  2547. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2548. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2549. var part3 = (cubed - (2.0 * squared)) + amount;
  2550. var part4 = cubed - squared;
  2551. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2552. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2553. return new Vector2(x, y);
  2554. };
  2555. /**
  2556. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2557. */
  2558. Vector2.Lerp = function (start, end, amount) {
  2559. var x = start.x + ((end.x - start.x) * amount);
  2560. var y = start.y + ((end.y - start.y) * amount);
  2561. return new Vector2(x, y);
  2562. };
  2563. /**
  2564. * Returns the dot product (float) of the vector "left" and the vector "right".
  2565. */
  2566. Vector2.Dot = function (left, right) {
  2567. return left.x * right.x + left.y * right.y;
  2568. };
  2569. /**
  2570. * Returns a new Vector2 equal to the normalized passed vector.
  2571. */
  2572. Vector2.Normalize = function (vector) {
  2573. var newVector = vector.clone();
  2574. newVector.normalize();
  2575. return newVector;
  2576. };
  2577. /**
  2578. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2579. */
  2580. Vector2.Minimize = function (left, right) {
  2581. var x = (left.x < right.x) ? left.x : right.x;
  2582. var y = (left.y < right.y) ? left.y : right.y;
  2583. return new Vector2(x, y);
  2584. };
  2585. /**
  2586. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2587. */
  2588. Vector2.Maximize = function (left, right) {
  2589. var x = (left.x > right.x) ? left.x : right.x;
  2590. var y = (left.y > right.y) ? left.y : right.y;
  2591. return new Vector2(x, y);
  2592. };
  2593. /**
  2594. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2595. */
  2596. Vector2.Transform = function (vector, transformation) {
  2597. var r = Vector2.Zero();
  2598. Vector2.TransformToRef(vector, transformation, r);
  2599. return r;
  2600. };
  2601. /**
  2602. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2603. */
  2604. Vector2.TransformToRef = function (vector, transformation, result) {
  2605. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2606. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2607. result.x = x;
  2608. result.y = y;
  2609. };
  2610. /**
  2611. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2612. */
  2613. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2614. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2615. var sign = a < 0 ? -1 : 1;
  2616. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2617. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2618. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2619. };
  2620. /**
  2621. * Returns the distance (float) between the vectors "value1" and "value2".
  2622. */
  2623. Vector2.Distance = function (value1, value2) {
  2624. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2625. };
  2626. /**
  2627. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2628. */
  2629. Vector2.DistanceSquared = function (value1, value2) {
  2630. var x = value1.x - value2.x;
  2631. var y = value1.y - value2.y;
  2632. return (x * x) + (y * y);
  2633. };
  2634. /**
  2635. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2636. */
  2637. Vector2.Center = function (value1, value2) {
  2638. var center = value1.add(value2);
  2639. center.scaleInPlace(0.5);
  2640. return center;
  2641. };
  2642. /**
  2643. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2644. */
  2645. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2646. var l2 = Vector2.DistanceSquared(segA, segB);
  2647. if (l2 === 0.0) {
  2648. return Vector2.Distance(p, segA);
  2649. }
  2650. var v = segB.subtract(segA);
  2651. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2652. var proj = segA.add(v.multiplyByFloats(t, t));
  2653. return Vector2.Distance(p, proj);
  2654. };
  2655. return Vector2;
  2656. }());
  2657. BABYLON.Vector2 = Vector2;
  2658. /**
  2659. * Classed used to store (x,y,z) vector representation
  2660. * A Vector3 is the main object used in 3D geometry
  2661. * It can represent etiher the coordinates of a point the space, either a direction
  2662. * Reminder: Babylon.js uses a left handed forward facing system
  2663. */
  2664. var Vector3 = /** @class */ (function () {
  2665. /**
  2666. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2667. * @param x defines the first coordinates (on X axis)
  2668. * @param y defines the second coordinates (on Y axis)
  2669. * @param z defines the third coordinates (on Z axis)
  2670. */
  2671. function Vector3(
  2672. /**
  2673. * Defines the first coordinates (on X axis)
  2674. */
  2675. x,
  2676. /**
  2677. * Defines the second coordinates (on Y axis)
  2678. */
  2679. y,
  2680. /**
  2681. * Defines the third coordinates (on Z axis)
  2682. */
  2683. z) {
  2684. this.x = x;
  2685. this.y = y;
  2686. this.z = z;
  2687. }
  2688. /**
  2689. * Creates a string representation of the Vector3
  2690. * @returns a string with the Vector3 coordinates.
  2691. */
  2692. Vector3.prototype.toString = function () {
  2693. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2694. };
  2695. /**
  2696. * Gets the class name
  2697. * @returns the string "Vector3"
  2698. */
  2699. Vector3.prototype.getClassName = function () {
  2700. return "Vector3";
  2701. };
  2702. /**
  2703. * Creates the Vector3 hash code
  2704. * @returns a number which tends to be unique between Vector3 instances
  2705. */
  2706. Vector3.prototype.getHashCode = function () {
  2707. var hash = this.x || 0;
  2708. hash = (hash * 397) ^ (this.y || 0);
  2709. hash = (hash * 397) ^ (this.z || 0);
  2710. return hash;
  2711. };
  2712. // Operators
  2713. /**
  2714. * Creates an array containing three elements : the coordinates of the Vector3
  2715. * @returns a new array of numbers
  2716. */
  2717. Vector3.prototype.asArray = function () {
  2718. var result = [];
  2719. this.toArray(result, 0);
  2720. return result;
  2721. };
  2722. /**
  2723. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2724. * @param array defines the destination array
  2725. * @param index defines the offset in the destination array
  2726. * @returns the current Vector3
  2727. */
  2728. Vector3.prototype.toArray = function (array, index) {
  2729. if (index === void 0) { index = 0; }
  2730. array[index] = this.x;
  2731. array[index + 1] = this.y;
  2732. array[index + 2] = this.z;
  2733. return this;
  2734. };
  2735. /**
  2736. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2737. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2738. */
  2739. Vector3.prototype.toQuaternion = function () {
  2740. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2741. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2742. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2743. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2744. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2745. var cosy = Math.cos(this.y * 0.5);
  2746. var siny = Math.sin(this.y * 0.5);
  2747. result.x = coszMinusx * siny;
  2748. result.y = -sinzMinusx * siny;
  2749. result.z = sinxPlusz * cosy;
  2750. result.w = cosxPlusz * cosy;
  2751. return result;
  2752. };
  2753. /**
  2754. * Adds the passed vector to the current Vector3
  2755. * @param otherVector defines the second operand
  2756. * @returns the current updated Vector3
  2757. */
  2758. Vector3.prototype.addInPlace = function (otherVector) {
  2759. this.x += otherVector.x;
  2760. this.y += otherVector.y;
  2761. this.z += otherVector.z;
  2762. return this;
  2763. };
  2764. /**
  2765. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2766. * @param otherVector defines the second operand
  2767. * @returns the resulting Vector3
  2768. */
  2769. Vector3.prototype.add = function (otherVector) {
  2770. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2771. };
  2772. /**
  2773. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2774. * @param otherVector defines the second operand
  2775. * @param result defines the Vector3 object where to store the result
  2776. * @returns the current Vector3
  2777. */
  2778. Vector3.prototype.addToRef = function (otherVector, result) {
  2779. result.x = this.x + otherVector.x;
  2780. result.y = this.y + otherVector.y;
  2781. result.z = this.z + otherVector.z;
  2782. return this;
  2783. };
  2784. /**
  2785. * Subtract the passed vector from the current Vector3
  2786. * @param otherVector defines the second operand
  2787. * @returns the current updated Vector3
  2788. */
  2789. Vector3.prototype.subtractInPlace = function (otherVector) {
  2790. this.x -= otherVector.x;
  2791. this.y -= otherVector.y;
  2792. this.z -= otherVector.z;
  2793. return this;
  2794. };
  2795. /**
  2796. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2797. * @param otherVector defines the second operand
  2798. * @returns the resulting Vector3
  2799. */
  2800. Vector3.prototype.subtract = function (otherVector) {
  2801. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2802. };
  2803. /**
  2804. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2805. * @param otherVector defines the second operand
  2806. * @param result defines the Vector3 object where to store the result
  2807. * @returns the current Vector3
  2808. */
  2809. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2810. result.x = this.x - otherVector.x;
  2811. result.y = this.y - otherVector.y;
  2812. result.z = this.z - otherVector.z;
  2813. return this;
  2814. };
  2815. /**
  2816. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2817. * @param x defines the x coordinate of the operand
  2818. * @param y defines the y coordinate of the operand
  2819. * @param z defines the z coordinate of the operand
  2820. * @returns the resulting Vector3
  2821. */
  2822. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2823. return new Vector3(this.x - x, this.y - y, this.z - z);
  2824. };
  2825. /**
  2826. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2827. * @param x defines the x coordinate of the operand
  2828. * @param y defines the y coordinate of the operand
  2829. * @param z defines the z coordinate of the operand
  2830. * @param result defines the Vector3 object where to store the result
  2831. * @returns the current Vector3
  2832. */
  2833. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2834. result.x = this.x - x;
  2835. result.y = this.y - y;
  2836. result.z = this.z - z;
  2837. return this;
  2838. };
  2839. /**
  2840. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2841. * @returns a new Vector3
  2842. */
  2843. Vector3.prototype.negate = function () {
  2844. return new Vector3(-this.x, -this.y, -this.z);
  2845. };
  2846. /**
  2847. * Multiplies the Vector3 coordinates by the float "scale"
  2848. * @param scale defines the multiplier factor
  2849. * @returns the current updated Vector3
  2850. */
  2851. Vector3.prototype.scaleInPlace = function (scale) {
  2852. this.x *= scale;
  2853. this.y *= scale;
  2854. this.z *= scale;
  2855. return this;
  2856. };
  2857. /**
  2858. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2859. * @param scale defines the multiplier factor
  2860. * @returns a new Vector3
  2861. */
  2862. Vector3.prototype.scale = function (scale) {
  2863. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2864. };
  2865. /**
  2866. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2867. * @param scale defines the multiplier factor
  2868. * @param result defines the Vector3 object where to store the result
  2869. * @returns the current Vector3
  2870. */
  2871. Vector3.prototype.scaleToRef = function (scale, result) {
  2872. result.x = this.x * scale;
  2873. result.y = this.y * scale;
  2874. result.z = this.z * scale;
  2875. return this;
  2876. };
  2877. /**
  2878. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2879. * @param scale defines the scale factor
  2880. * @param result defines the Vector3 object where to store the result
  2881. * @returns the unmodified current Vector3
  2882. */
  2883. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2884. result.x += this.x * scale;
  2885. result.y += this.y * scale;
  2886. result.z += this.z * scale;
  2887. return this;
  2888. };
  2889. /**
  2890. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2891. * @param otherVector defines the second operand
  2892. * @returns true if both vectors are equals
  2893. */
  2894. Vector3.prototype.equals = function (otherVector) {
  2895. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2896. };
  2897. /**
  2898. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2899. * @param otherVector defines the second operand
  2900. * @param epsilon defines the minimal distance to define values as equals
  2901. * @returns true if both vectors are distant less than epsilon
  2902. */
  2903. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2904. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2905. 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);
  2906. };
  2907. /**
  2908. * Returns true if the current Vector3 coordinates equals the passed floats
  2909. * @param x defines the x coordinate of the operand
  2910. * @param y defines the y coordinate of the operand
  2911. * @param z defines the z coordinate of the operand
  2912. * @returns true if both vectors are equals
  2913. */
  2914. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2915. return this.x === x && this.y === y && this.z === z;
  2916. };
  2917. /**
  2918. * Multiplies the current Vector3 coordinates by the passed ones
  2919. * @param otherVector defines the second operand
  2920. * @returns the current updated Vector3
  2921. */
  2922. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2923. this.x *= otherVector.x;
  2924. this.y *= otherVector.y;
  2925. this.z *= otherVector.z;
  2926. return this;
  2927. };
  2928. /**
  2929. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2930. * @param otherVector defines the second operand
  2931. * @returns the new Vector3
  2932. */
  2933. Vector3.prototype.multiply = function (otherVector) {
  2934. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2935. };
  2936. /**
  2937. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2938. * @param otherVector defines the second operand
  2939. * @param result defines the Vector3 object where to store the result
  2940. * @returns the current Vector3
  2941. */
  2942. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2943. result.x = this.x * otherVector.x;
  2944. result.y = this.y * otherVector.y;
  2945. result.z = this.z * otherVector.z;
  2946. return this;
  2947. };
  2948. /**
  2949. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2950. * @param x defines the x coordinate of the operand
  2951. * @param y defines the y coordinate of the operand
  2952. * @param z defines the z coordinate of the operand
  2953. * @returns the new Vector3
  2954. */
  2955. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2956. return new Vector3(this.x * x, this.y * y, this.z * z);
  2957. };
  2958. /**
  2959. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2960. * @param otherVector defines the second operand
  2961. * @returns the new Vector3
  2962. */
  2963. Vector3.prototype.divide = function (otherVector) {
  2964. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2965. };
  2966. /**
  2967. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2968. * @param otherVector defines the second operand
  2969. * @param result defines the Vector3 object where to store the result
  2970. * @returns the current Vector3
  2971. */
  2972. Vector3.prototype.divideToRef = function (otherVector, result) {
  2973. result.x = this.x / otherVector.x;
  2974. result.y = this.y / otherVector.y;
  2975. result.z = this.z / otherVector.z;
  2976. return this;
  2977. };
  2978. /**
  2979. * Divides the current Vector3 coordinates by the passed ones.
  2980. * @param otherVector defines the second operand
  2981. * @returns the current updated Vector3
  2982. */
  2983. Vector3.prototype.divideInPlace = function (otherVector) {
  2984. return this.divideToRef(otherVector, this);
  2985. };
  2986. /**
  2987. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2988. * @param other defines the second operand
  2989. * @returns the current updated Vector3
  2990. */
  2991. Vector3.prototype.minimizeInPlace = function (other) {
  2992. if (other.x < this.x)
  2993. this.x = other.x;
  2994. if (other.y < this.y)
  2995. this.y = other.y;
  2996. if (other.z < this.z)
  2997. this.z = other.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3002. * @param other defines the second operand
  3003. * @returns the current updated Vector3
  3004. */
  3005. Vector3.prototype.maximizeInPlace = function (other) {
  3006. if (other.x > this.x)
  3007. this.x = other.x;
  3008. if (other.y > this.y)
  3009. this.y = other.y;
  3010. if (other.z > this.z)
  3011. this.z = other.z;
  3012. return this;
  3013. };
  3014. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3015. /**
  3016. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3017. */
  3018. get: function () {
  3019. var absX = Math.abs(this.x);
  3020. var absY = Math.abs(this.y);
  3021. if (absX !== absY) {
  3022. return true;
  3023. }
  3024. var absZ = Math.abs(this.z);
  3025. if (absX !== absZ) {
  3026. return true;
  3027. }
  3028. if (absY !== absZ) {
  3029. return true;
  3030. }
  3031. return false;
  3032. },
  3033. enumerable: true,
  3034. configurable: true
  3035. });
  3036. // Properties
  3037. /**
  3038. * Gets the length of the Vector3
  3039. * @returns the length of the Vecto3
  3040. */
  3041. Vector3.prototype.length = function () {
  3042. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3043. };
  3044. /**
  3045. * Gets the squared length of the Vector3
  3046. * @returns squared length of the Vector3
  3047. */
  3048. Vector3.prototype.lengthSquared = function () {
  3049. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3050. };
  3051. /**
  3052. * Normalize the current Vector3.
  3053. * Please note that this is an in place operation.
  3054. * @returns the current updated Vector3
  3055. */
  3056. Vector3.prototype.normalize = function () {
  3057. var len = this.length();
  3058. if (len === 0 || len === 1.0)
  3059. return this;
  3060. var num = 1.0 / len;
  3061. this.x *= num;
  3062. this.y *= num;
  3063. this.z *= num;
  3064. return this;
  3065. };
  3066. /**
  3067. * Normalize the current Vector3 to a new vector
  3068. * @returns the new Vector3
  3069. */
  3070. Vector3.prototype.normalizeToNew = function () {
  3071. var normalized = new Vector3(0, 0, 0);
  3072. this.normalizeToRef(normalized);
  3073. return normalized;
  3074. };
  3075. /**
  3076. * Normalize the current Vector3 to the reference
  3077. * @param reference define the Vector3 to update
  3078. * @returns the updated Vector3
  3079. */
  3080. Vector3.prototype.normalizeToRef = function (reference) {
  3081. var len = this.length();
  3082. if (len === 0 || len === 1.0) {
  3083. reference.set(this.x, this.y, this.z);
  3084. return reference;
  3085. }
  3086. var scale = 1.0 / len;
  3087. this.scaleToRef(scale, reference);
  3088. return reference;
  3089. };
  3090. /**
  3091. * Creates a new Vector3 copied from the current Vector3
  3092. * @returns the new Vector3
  3093. */
  3094. Vector3.prototype.clone = function () {
  3095. return new Vector3(this.x, this.y, this.z);
  3096. };
  3097. /**
  3098. * Copies the passed vector coordinates to the current Vector3 ones
  3099. * @param source defines the source Vector3
  3100. * @returns the current updated Vector3
  3101. */
  3102. Vector3.prototype.copyFrom = function (source) {
  3103. this.x = source.x;
  3104. this.y = source.y;
  3105. this.z = source.z;
  3106. return this;
  3107. };
  3108. /**
  3109. * Copies the passed floats to the current Vector3 coordinates
  3110. * @param x defines the x coordinate of the operand
  3111. * @param y defines the y coordinate of the operand
  3112. * @param z defines the z coordinate of the operand
  3113. * @returns the current updated Vector3
  3114. */
  3115. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3116. this.x = x;
  3117. this.y = y;
  3118. this.z = z;
  3119. return this;
  3120. };
  3121. /**
  3122. * Copies the passed floats to the current Vector3 coordinates
  3123. * @param x defines the x coordinate of the operand
  3124. * @param y defines the y coordinate of the operand
  3125. * @param z defines the z coordinate of the operand
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.set = function (x, y, z) {
  3129. return this.copyFromFloats(x, y, z);
  3130. };
  3131. // Statics
  3132. /**
  3133. * Get the clip factor between two vectors
  3134. * @param vector0 defines the first operand
  3135. * @param vector1 defines the second operand
  3136. * @param axis defines the axis to use
  3137. * @param size defines the size along the axis
  3138. * @returns the clip factor
  3139. */
  3140. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3141. var d0 = Vector3.Dot(vector0, axis) - size;
  3142. var d1 = Vector3.Dot(vector1, axis) - size;
  3143. var s = d0 / (d0 - d1);
  3144. return s;
  3145. };
  3146. /**
  3147. * Get angle between two vectors
  3148. * @param vector0 angle between vector0 and vector1
  3149. * @param vector1 angle between vector0 and vector1
  3150. * @param normal direction of the normal
  3151. * @return the angle between vector0 and vector1
  3152. */
  3153. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3154. var v0 = vector0.clone().normalize();
  3155. var v1 = vector1.clone().normalize();
  3156. var dot = Vector3.Dot(v0, v1);
  3157. var n = Vector3.Cross(v0, v1);
  3158. if (Vector3.Dot(n, normal) > 0) {
  3159. return Math.acos(dot);
  3160. }
  3161. return -Math.acos(dot);
  3162. };
  3163. /**
  3164. * Returns a new Vector3 set from the index "offset" of the passed array
  3165. * @param array defines the source array
  3166. * @param offset defines the offset in the source array
  3167. * @returns the new Vector3
  3168. */
  3169. Vector3.FromArray = function (array, offset) {
  3170. if (!offset) {
  3171. offset = 0;
  3172. }
  3173. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3174. };
  3175. /**
  3176. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3177. * This function is deprecated. Use FromArray instead
  3178. * @param array defines the source array
  3179. * @param offset defines the offset in the source array
  3180. * @returns the new Vector3
  3181. */
  3182. Vector3.FromFloatArray = function (array, offset) {
  3183. return Vector3.FromArray(array, offset);
  3184. };
  3185. /**
  3186. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3187. * @param array defines the source array
  3188. * @param offset defines the offset in the source array
  3189. * @param result defines the Vector3 where to store the result
  3190. */
  3191. Vector3.FromArrayToRef = function (array, offset, result) {
  3192. result.x = array[offset];
  3193. result.y = array[offset + 1];
  3194. result.z = array[offset + 2];
  3195. };
  3196. /**
  3197. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3198. * This function is deprecated. Use FromArrayToRef instead.
  3199. * @param array defines the source array
  3200. * @param offset defines the offset in the source array
  3201. * @param result defines the Vector3 where to store the result
  3202. */
  3203. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3204. return Vector3.FromArrayToRef(array, offset, result);
  3205. };
  3206. /**
  3207. * Sets the passed vector "result" with the passed floats.
  3208. * @param x defines the x coordinate of the source
  3209. * @param y defines the y coordinate of the source
  3210. * @param z defines the z coordinate of the source
  3211. * @param result defines the Vector3 where to store the result
  3212. */
  3213. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3214. result.x = x;
  3215. result.y = y;
  3216. result.z = z;
  3217. };
  3218. /**
  3219. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3220. * @returns a new empty Vector3
  3221. */
  3222. Vector3.Zero = function () {
  3223. return new Vector3(0.0, 0.0, 0.0);
  3224. };
  3225. /**
  3226. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3227. * @returns a new unit Vector3
  3228. */
  3229. Vector3.One = function () {
  3230. return new Vector3(1.0, 1.0, 1.0);
  3231. };
  3232. /**
  3233. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3234. * @returns a new up Vector3
  3235. */
  3236. Vector3.Up = function () {
  3237. return new Vector3(0.0, 1.0, 0.0);
  3238. };
  3239. /**
  3240. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3241. * @returns a new forward Vector3
  3242. */
  3243. Vector3.Forward = function () {
  3244. return new Vector3(0.0, 0.0, 1.0);
  3245. };
  3246. /**
  3247. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3248. * @returns a new right Vector3
  3249. */
  3250. Vector3.Right = function () {
  3251. return new Vector3(1.0, 0.0, 0.0);
  3252. };
  3253. /**
  3254. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3255. * @returns a new left Vector3
  3256. */
  3257. Vector3.Left = function () {
  3258. return new Vector3(-1.0, 0.0, 0.0);
  3259. };
  3260. /**
  3261. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3262. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3263. * @param vector defines the Vector3 to transform
  3264. * @param transformation defines the transformation matrix
  3265. * @returns the transformed Vector3
  3266. */
  3267. Vector3.TransformCoordinates = function (vector, transformation) {
  3268. var result = Vector3.Zero();
  3269. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3270. return result;
  3271. };
  3272. /**
  3273. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3274. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3275. * @param vector defines the Vector3 to transform
  3276. * @param transformation defines the transformation matrix
  3277. * @param result defines the Vector3 where to store the result
  3278. */
  3279. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3280. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3281. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3282. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3283. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3284. result.x = x / w;
  3285. result.y = y / w;
  3286. result.z = z / w;
  3287. };
  3288. /**
  3289. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3290. * This method computes tranformed coordinates only, not transformed direction vectors
  3291. * @param x define the x coordinate of the source vector
  3292. * @param y define the y coordinate of the source vector
  3293. * @param z define the z coordinate of the source vector
  3294. * @param transformation defines the transformation matrix
  3295. * @param result defines the Vector3 where to store the result
  3296. */
  3297. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3298. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3299. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3300. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3301. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3302. result.x = rx / rw;
  3303. result.y = ry / rw;
  3304. result.z = rz / rw;
  3305. };
  3306. /**
  3307. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3308. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3309. * @param vector defines the Vector3 to transform
  3310. * @param transformation defines the transformation matrix
  3311. * @returns the new Vector3
  3312. */
  3313. Vector3.TransformNormal = function (vector, transformation) {
  3314. var result = Vector3.Zero();
  3315. Vector3.TransformNormalToRef(vector, transformation, result);
  3316. return result;
  3317. };
  3318. /**
  3319. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3320. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3321. * @param vector defines the Vector3 to transform
  3322. * @param transformation defines the transformation matrix
  3323. * @param result defines the Vector3 where to store the result
  3324. */
  3325. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3326. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3327. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3328. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3329. result.x = x;
  3330. result.y = y;
  3331. result.z = z;
  3332. };
  3333. /**
  3334. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3335. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3336. * @param x define the x coordinate of the source vector
  3337. * @param y define the y coordinate of the source vector
  3338. * @param z define the z coordinate of the source vector
  3339. * @param transformation defines the transformation matrix
  3340. * @param result defines the Vector3 where to store the result
  3341. */
  3342. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3343. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3344. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3345. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3349. * @param value1 defines the first control point
  3350. * @param value2 defines the second control point
  3351. * @param value3 defines the third control point
  3352. * @param value4 defines the fourth control point
  3353. * @param amount defines the amount on the spline to use
  3354. * @returns the new Vector3
  3355. */
  3356. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3357. var squared = amount * amount;
  3358. var cubed = amount * squared;
  3359. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3360. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3361. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3362. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3363. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3364. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3365. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3366. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3367. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3368. return new Vector3(x, y, z);
  3369. };
  3370. /**
  3371. * 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"
  3372. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3373. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3374. * @param value defines the current value
  3375. * @param min defines the lower range value
  3376. * @param max defines the upper range value
  3377. * @returns the new Vector3
  3378. */
  3379. Vector3.Clamp = function (value, min, max) {
  3380. var x = value.x;
  3381. x = (x > max.x) ? max.x : x;
  3382. x = (x < min.x) ? min.x : x;
  3383. var y = value.y;
  3384. y = (y > max.y) ? max.y : y;
  3385. y = (y < min.y) ? min.y : y;
  3386. var z = value.z;
  3387. z = (z > max.z) ? max.z : z;
  3388. z = (z < min.z) ? min.z : z;
  3389. return new Vector3(x, y, z);
  3390. };
  3391. /**
  3392. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3393. * @param value1 defines the first control point
  3394. * @param tangent1 defines the first tangent vector
  3395. * @param value2 defines the second control point
  3396. * @param tangent2 defines the second tangent vector
  3397. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3398. * @returns the new Vector3
  3399. */
  3400. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3401. var squared = amount * amount;
  3402. var cubed = amount * squared;
  3403. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3404. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3405. var part3 = (cubed - (2.0 * squared)) + amount;
  3406. var part4 = cubed - squared;
  3407. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3408. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3409. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3410. return new Vector3(x, y, z);
  3411. };
  3412. /**
  3413. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3414. * @param start defines the start value
  3415. * @param end defines the end value
  3416. * @param amount max defines amount between both (between 0 and 1)
  3417. * @returns the new Vector3
  3418. */
  3419. Vector3.Lerp = function (start, end, amount) {
  3420. var result = new Vector3(0, 0, 0);
  3421. Vector3.LerpToRef(start, end, amount, result);
  3422. return result;
  3423. };
  3424. /**
  3425. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3426. * @param start defines the start value
  3427. * @param end defines the end value
  3428. * @param amount max defines amount between both (between 0 and 1)
  3429. * @param result defines the Vector3 where to store the result
  3430. */
  3431. Vector3.LerpToRef = function (start, end, amount, result) {
  3432. result.x = start.x + ((end.x - start.x) * amount);
  3433. result.y = start.y + ((end.y - start.y) * amount);
  3434. result.z = start.z + ((end.z - start.z) * amount);
  3435. };
  3436. /**
  3437. * Returns the dot product (float) between the vectors "left" and "right"
  3438. * @param left defines the left operand
  3439. * @param right defines the right operand
  3440. * @returns the dot product
  3441. */
  3442. Vector3.Dot = function (left, right) {
  3443. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3444. };
  3445. /**
  3446. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3447. * The cross product is then orthogonal to both "left" and "right"
  3448. * @param left defines the left operand
  3449. * @param right defines the right operand
  3450. * @returns the cross product
  3451. */
  3452. Vector3.Cross = function (left, right) {
  3453. var result = Vector3.Zero();
  3454. Vector3.CrossToRef(left, right, result);
  3455. return result;
  3456. };
  3457. /**
  3458. * Sets the passed vector "result" with the cross product of "left" and "right"
  3459. * The cross product is then orthogonal to both "left" and "right"
  3460. * @param left defines the left operand
  3461. * @param right defines the right operand
  3462. * @param result defines the Vector3 where to store the result
  3463. */
  3464. Vector3.CrossToRef = function (left, right, result) {
  3465. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3466. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3467. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3468. result.copyFrom(MathTmp.Vector3[0]);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 as the normalization of the passed vector
  3472. * @param vector defines the Vector3 to normalize
  3473. * @returns the new Vector3
  3474. */
  3475. Vector3.Normalize = function (vector) {
  3476. var result = Vector3.Zero();
  3477. Vector3.NormalizeToRef(vector, result);
  3478. return result;
  3479. };
  3480. /**
  3481. * Sets the passed vector "result" with the normalization of the passed first vector
  3482. * @param vector defines the Vector3 to normalize
  3483. * @param result defines the Vector3 where to store the result
  3484. */
  3485. Vector3.NormalizeToRef = function (vector, result) {
  3486. result.copyFrom(vector);
  3487. result.normalize();
  3488. };
  3489. /**
  3490. * Project a Vector3 onto screen space
  3491. * @param vector defines the Vector3 to project
  3492. * @param world defines the world matrix to use
  3493. * @param transform defines the transform (view x projection) matrix to use
  3494. * @param viewport defines the screen viewport to use
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Project = function (vector, world, transform, viewport) {
  3498. var cw = viewport.width;
  3499. var ch = viewport.height;
  3500. var cx = viewport.x;
  3501. var cy = viewport.y;
  3502. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3503. 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);
  3504. var matrix = MathTmp.Matrix[0];
  3505. world.multiplyToRef(transform, matrix);
  3506. matrix.multiplyToRef(viewportMatrix, matrix);
  3507. return Vector3.TransformCoordinates(vector, matrix);
  3508. };
  3509. /**
  3510. * Unproject from screen space to object space
  3511. * @param source defines the screen space Vector3 to use
  3512. * @param viewportWidth defines the current width of the viewport
  3513. * @param viewportHeight defines the current height of the viewport
  3514. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3515. * @param transform defines the transform (view x projection) matrix to use
  3516. * @returns the new Vector3
  3517. */
  3518. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3519. var matrix = MathTmp.Matrix[0];
  3520. world.multiplyToRef(transform, matrix);
  3521. matrix.invert();
  3522. source.x = source.x / viewportWidth * 2 - 1;
  3523. source.y = -(source.y / viewportHeight * 2 - 1);
  3524. var vector = Vector3.TransformCoordinates(source, matrix);
  3525. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3526. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3527. vector = vector.scale(1.0 / num);
  3528. }
  3529. return vector;
  3530. };
  3531. /**
  3532. * Unproject from screen space to object space
  3533. * @param source defines the screen space Vector3 to use
  3534. * @param viewportWidth defines the current width of the viewport
  3535. * @param viewportHeight defines the current height of the viewport
  3536. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3537. * @param view defines the view matrix to use
  3538. * @param projection defines the projection matrix to use
  3539. * @returns the new Vector3
  3540. */
  3541. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3542. var result = Vector3.Zero();
  3543. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3544. return result;
  3545. };
  3546. /**
  3547. * Unproject from screen space to object space
  3548. * @param source defines the screen space Vector3 to use
  3549. * @param viewportWidth defines the current width of the viewport
  3550. * @param viewportHeight defines the current height of the viewport
  3551. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3552. * @param view defines the view matrix to use
  3553. * @param projection defines the projection matrix to use
  3554. * @param result defines the Vector3 where to store the result
  3555. */
  3556. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3557. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3558. };
  3559. /**
  3560. * Unproject from screen space to object space
  3561. * @param sourceX defines the screen space x coordinate to use
  3562. * @param sourceY defines the screen space y coordinate to use
  3563. * @param sourceZ defines the screen space z coordinate to use
  3564. * @param viewportWidth defines the current width of the viewport
  3565. * @param viewportHeight defines the current height of the viewport
  3566. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3567. * @param view defines the view matrix to use
  3568. * @param projection defines the projection matrix to use
  3569. * @param result defines the Vector3 where to store the result
  3570. */
  3571. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3572. var matrix = MathTmp.Matrix[0];
  3573. world.multiplyToRef(view, matrix);
  3574. matrix.multiplyToRef(projection, matrix);
  3575. matrix.invert();
  3576. var screenSource = MathTmp.Vector3[0];
  3577. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3578. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3579. screenSource.z = 2 * sourceZ - 1.0;
  3580. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3581. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3582. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3583. result.scaleInPlace(1.0 / num);
  3584. }
  3585. };
  3586. /**
  3587. * Gets the minimal coordinate values between two Vector3
  3588. * @param left defines the first operand
  3589. * @param right defines the second operand
  3590. * @returns the new Vector3
  3591. */
  3592. Vector3.Minimize = function (left, right) {
  3593. var min = left.clone();
  3594. min.minimizeInPlace(right);
  3595. return min;
  3596. };
  3597. /**
  3598. * Gets the maximal coordinate values between two Vector3
  3599. * @param left defines the first operand
  3600. * @param right defines the second operand
  3601. * @returns the new Vector3
  3602. */
  3603. Vector3.Maximize = function (left, right) {
  3604. var max = left.clone();
  3605. max.maximizeInPlace(right);
  3606. return max;
  3607. };
  3608. /**
  3609. * Returns the distance between the vectors "value1" and "value2"
  3610. * @param value1 defines the first operand
  3611. * @param value2 defines the second operand
  3612. * @returns the distance
  3613. */
  3614. Vector3.Distance = function (value1, value2) {
  3615. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3616. };
  3617. /**
  3618. * Returns the squared distance between the vectors "value1" and "value2"
  3619. * @param value1 defines the first operand
  3620. * @param value2 defines the second operand
  3621. * @returns the squared distance
  3622. */
  3623. Vector3.DistanceSquared = function (value1, value2) {
  3624. var x = value1.x - value2.x;
  3625. var y = value1.y - value2.y;
  3626. var z = value1.z - value2.z;
  3627. return (x * x) + (y * y) + (z * z);
  3628. };
  3629. /**
  3630. * Returns a new Vector3 located at the center between "value1" and "value2"
  3631. * @param value1 defines the first operand
  3632. * @param value2 defines the second operand
  3633. * @returns the new Vector3
  3634. */
  3635. Vector3.Center = function (value1, value2) {
  3636. var center = value1.add(value2);
  3637. center.scaleInPlace(0.5);
  3638. return center;
  3639. };
  3640. /**
  3641. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3642. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3643. * to something in order to rotate it from its local system to the given target system
  3644. * Note: axis1, axis2 and axis3 are normalized during this operation
  3645. * @param axis1 defines the first axis
  3646. * @param axis2 defines the second axis
  3647. * @param axis3 defines the third axis
  3648. * @returns a new Vector3
  3649. */
  3650. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3651. var rotation = Vector3.Zero();
  3652. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3653. return rotation;
  3654. };
  3655. /**
  3656. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3657. * @param axis1 defines the first axis
  3658. * @param axis2 defines the second axis
  3659. * @param axis3 defines the third axis
  3660. * @param ref defines the Vector3 where to store the result
  3661. */
  3662. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3663. var quat = MathTmp.Quaternion[0];
  3664. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3665. quat.toEulerAnglesToRef(ref);
  3666. };
  3667. return Vector3;
  3668. }());
  3669. BABYLON.Vector3 = Vector3;
  3670. //Vector4 class created for EulerAngle class conversion to Quaternion
  3671. var Vector4 = /** @class */ (function () {
  3672. /**
  3673. * Creates a Vector4 object from the passed floats.
  3674. */
  3675. function Vector4(x, y, z, w) {
  3676. this.x = x;
  3677. this.y = y;
  3678. this.z = z;
  3679. this.w = w;
  3680. }
  3681. /**
  3682. * Returns the string with the Vector4 coordinates.
  3683. */
  3684. Vector4.prototype.toString = function () {
  3685. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3686. };
  3687. /**
  3688. * Returns the string "Vector4".
  3689. */
  3690. Vector4.prototype.getClassName = function () {
  3691. return "Vector4";
  3692. };
  3693. /**
  3694. * Returns the Vector4 hash code.
  3695. */
  3696. Vector4.prototype.getHashCode = function () {
  3697. var hash = this.x || 0;
  3698. hash = (hash * 397) ^ (this.y || 0);
  3699. hash = (hash * 397) ^ (this.z || 0);
  3700. hash = (hash * 397) ^ (this.w || 0);
  3701. return hash;
  3702. };
  3703. // Operators
  3704. /**
  3705. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3706. */
  3707. Vector4.prototype.asArray = function () {
  3708. var result = new Array();
  3709. this.toArray(result, 0);
  3710. return result;
  3711. };
  3712. /**
  3713. * Populates the passed array from the passed index with the Vector4 coordinates.
  3714. * Returns the Vector4.
  3715. */
  3716. Vector4.prototype.toArray = function (array, index) {
  3717. if (index === undefined) {
  3718. index = 0;
  3719. }
  3720. array[index] = this.x;
  3721. array[index + 1] = this.y;
  3722. array[index + 2] = this.z;
  3723. array[index + 3] = this.w;
  3724. return this;
  3725. };
  3726. /**
  3727. * Adds the passed vector to the current Vector4.
  3728. * Returns the updated Vector4.
  3729. */
  3730. Vector4.prototype.addInPlace = function (otherVector) {
  3731. this.x += otherVector.x;
  3732. this.y += otherVector.y;
  3733. this.z += otherVector.z;
  3734. this.w += otherVector.w;
  3735. return this;
  3736. };
  3737. /**
  3738. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3739. */
  3740. Vector4.prototype.add = function (otherVector) {
  3741. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3742. };
  3743. /**
  3744. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3745. * Returns the current Vector4.
  3746. */
  3747. Vector4.prototype.addToRef = function (otherVector, result) {
  3748. result.x = this.x + otherVector.x;
  3749. result.y = this.y + otherVector.y;
  3750. result.z = this.z + otherVector.z;
  3751. result.w = this.w + otherVector.w;
  3752. return this;
  3753. };
  3754. /**
  3755. * Subtract in place the passed vector from the current Vector4.
  3756. * Returns the updated Vector4.
  3757. */
  3758. Vector4.prototype.subtractInPlace = function (otherVector) {
  3759. this.x -= otherVector.x;
  3760. this.y -= otherVector.y;
  3761. this.z -= otherVector.z;
  3762. this.w -= otherVector.w;
  3763. return this;
  3764. };
  3765. /**
  3766. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3767. */
  3768. Vector4.prototype.subtract = function (otherVector) {
  3769. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3770. };
  3771. /**
  3772. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3773. * Returns the current Vector4.
  3774. */
  3775. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3776. result.x = this.x - otherVector.x;
  3777. result.y = this.y - otherVector.y;
  3778. result.z = this.z - otherVector.z;
  3779. result.w = this.w - otherVector.w;
  3780. return this;
  3781. };
  3782. /**
  3783. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3784. */
  3785. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3786. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3787. };
  3788. /**
  3789. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3790. * Returns the current Vector4.
  3791. */
  3792. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3793. result.x = this.x - x;
  3794. result.y = this.y - y;
  3795. result.z = this.z - z;
  3796. result.w = this.w - w;
  3797. return this;
  3798. };
  3799. /**
  3800. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3801. */
  3802. Vector4.prototype.negate = function () {
  3803. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3804. };
  3805. /**
  3806. * Multiplies the current Vector4 coordinates by scale (float).
  3807. * Returns the updated Vector4.
  3808. */
  3809. Vector4.prototype.scaleInPlace = function (scale) {
  3810. this.x *= scale;
  3811. this.y *= scale;
  3812. this.z *= scale;
  3813. this.w *= scale;
  3814. return this;
  3815. };
  3816. /**
  3817. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3818. */
  3819. Vector4.prototype.scale = function (scale) {
  3820. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3821. };
  3822. /**
  3823. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3824. * Returns the current Vector4.
  3825. */
  3826. Vector4.prototype.scaleToRef = function (scale, result) {
  3827. result.x = this.x * scale;
  3828. result.y = this.y * scale;
  3829. result.z = this.z * scale;
  3830. result.w = this.w * scale;
  3831. return this;
  3832. };
  3833. /**
  3834. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3835. * @param scale defines the scale factor
  3836. * @param result defines the Vector4 object where to store the result
  3837. * @returns the unmodified current Vector4
  3838. */
  3839. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3840. result.x += this.x * scale;
  3841. result.y += this.y * scale;
  3842. result.z += this.z * scale;
  3843. result.w += this.w * scale;
  3844. return this;
  3845. };
  3846. /**
  3847. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3848. */
  3849. Vector4.prototype.equals = function (otherVector) {
  3850. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3851. };
  3852. /**
  3853. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3854. */
  3855. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3856. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3857. return otherVector
  3858. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3859. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3860. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3861. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3862. };
  3863. /**
  3864. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3865. */
  3866. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3867. return this.x === x && this.y === y && this.z === z && this.w === w;
  3868. };
  3869. /**
  3870. * Multiplies in place the current Vector4 by the passed one.
  3871. * Returns the updated Vector4.
  3872. */
  3873. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3874. this.x *= otherVector.x;
  3875. this.y *= otherVector.y;
  3876. this.z *= otherVector.z;
  3877. this.w *= otherVector.w;
  3878. return this;
  3879. };
  3880. /**
  3881. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3882. */
  3883. Vector4.prototype.multiply = function (otherVector) {
  3884. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3885. };
  3886. /**
  3887. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3888. * Returns the current Vector4.
  3889. */
  3890. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3891. result.x = this.x * otherVector.x;
  3892. result.y = this.y * otherVector.y;
  3893. result.z = this.z * otherVector.z;
  3894. result.w = this.w * otherVector.w;
  3895. return this;
  3896. };
  3897. /**
  3898. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3899. */
  3900. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3901. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3902. };
  3903. /**
  3904. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3905. */
  3906. Vector4.prototype.divide = function (otherVector) {
  3907. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3908. };
  3909. /**
  3910. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3911. * Returns the current Vector4.
  3912. */
  3913. Vector4.prototype.divideToRef = function (otherVector, result) {
  3914. result.x = this.x / otherVector.x;
  3915. result.y = this.y / otherVector.y;
  3916. result.z = this.z / otherVector.z;
  3917. result.w = this.w / otherVector.w;
  3918. return this;
  3919. };
  3920. /**
  3921. * Divides the current Vector3 coordinates by the passed ones.
  3922. * @returns the updated Vector3.
  3923. */
  3924. Vector4.prototype.divideInPlace = function (otherVector) {
  3925. return this.divideToRef(otherVector, this);
  3926. };
  3927. /**
  3928. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3929. * @param other defines the second operand
  3930. * @returns the current updated Vector4
  3931. */
  3932. Vector4.prototype.minimizeInPlace = function (other) {
  3933. if (other.x < this.x)
  3934. this.x = other.x;
  3935. if (other.y < this.y)
  3936. this.y = other.y;
  3937. if (other.z < this.z)
  3938. this.z = other.z;
  3939. if (other.w < this.w)
  3940. this.w = other.w;
  3941. return this;
  3942. };
  3943. /**
  3944. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3945. * @param other defines the second operand
  3946. * @returns the current updated Vector4
  3947. */
  3948. Vector4.prototype.maximizeInPlace = function (other) {
  3949. if (other.x > this.x)
  3950. this.x = other.x;
  3951. if (other.y > this.y)
  3952. this.y = other.y;
  3953. if (other.z > this.z)
  3954. this.z = other.z;
  3955. if (other.w > this.w)
  3956. this.w = other.w;
  3957. return this;
  3958. };
  3959. // Properties
  3960. /**
  3961. * Returns the Vector4 length (float).
  3962. */
  3963. Vector4.prototype.length = function () {
  3964. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3965. };
  3966. /**
  3967. * Returns the Vector4 squared length (float).
  3968. */
  3969. Vector4.prototype.lengthSquared = function () {
  3970. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3971. };
  3972. // Methods
  3973. /**
  3974. * Normalizes in place the Vector4.
  3975. * Returns the updated Vector4.
  3976. */
  3977. Vector4.prototype.normalize = function () {
  3978. var len = this.length();
  3979. if (len === 0)
  3980. return this;
  3981. var num = 1.0 / len;
  3982. this.x *= num;
  3983. this.y *= num;
  3984. this.z *= num;
  3985. this.w *= num;
  3986. return this;
  3987. };
  3988. /**
  3989. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3990. */
  3991. Vector4.prototype.toVector3 = function () {
  3992. return new Vector3(this.x, this.y, this.z);
  3993. };
  3994. /**
  3995. * Returns a new Vector4 copied from the current one.
  3996. */
  3997. Vector4.prototype.clone = function () {
  3998. return new Vector4(this.x, this.y, this.z, this.w);
  3999. };
  4000. /**
  4001. * Updates the current Vector4 with the passed one coordinates.
  4002. * Returns the updated Vector4.
  4003. */
  4004. Vector4.prototype.copyFrom = function (source) {
  4005. this.x = source.x;
  4006. this.y = source.y;
  4007. this.z = source.z;
  4008. this.w = source.w;
  4009. return this;
  4010. };
  4011. /**
  4012. * Updates the current Vector4 coordinates with the passed floats.
  4013. * Returns the updated Vector4.
  4014. */
  4015. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4016. this.x = x;
  4017. this.y = y;
  4018. this.z = z;
  4019. this.w = w;
  4020. return this;
  4021. };
  4022. /**
  4023. * Updates the current Vector4 coordinates with the passed floats.
  4024. * Returns the updated Vector4.
  4025. */
  4026. Vector4.prototype.set = function (x, y, z, w) {
  4027. return this.copyFromFloats(x, y, z, w);
  4028. };
  4029. // Statics
  4030. /**
  4031. * Returns a new Vector4 set from the starting index of the passed array.
  4032. */
  4033. Vector4.FromArray = function (array, offset) {
  4034. if (!offset) {
  4035. offset = 0;
  4036. }
  4037. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4038. };
  4039. /**
  4040. * Updates the passed vector "result" from the starting index of the passed array.
  4041. */
  4042. Vector4.FromArrayToRef = function (array, offset, result) {
  4043. result.x = array[offset];
  4044. result.y = array[offset + 1];
  4045. result.z = array[offset + 2];
  4046. result.w = array[offset + 3];
  4047. };
  4048. /**
  4049. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4050. */
  4051. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4052. Vector4.FromArrayToRef(array, offset, result);
  4053. };
  4054. /**
  4055. * Updates the passed vector "result" coordinates from the passed floats.
  4056. */
  4057. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4058. result.x = x;
  4059. result.y = y;
  4060. result.z = z;
  4061. result.w = w;
  4062. };
  4063. /**
  4064. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4065. */
  4066. Vector4.Zero = function () {
  4067. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4068. };
  4069. /**
  4070. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4071. */
  4072. Vector4.One = function () {
  4073. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4074. };
  4075. /**
  4076. * Returns a new normalized Vector4 from the passed one.
  4077. */
  4078. Vector4.Normalize = function (vector) {
  4079. var result = Vector4.Zero();
  4080. Vector4.NormalizeToRef(vector, result);
  4081. return result;
  4082. };
  4083. /**
  4084. * Updates the passed vector "result" from the normalization of the passed one.
  4085. */
  4086. Vector4.NormalizeToRef = function (vector, result) {
  4087. result.copyFrom(vector);
  4088. result.normalize();
  4089. };
  4090. Vector4.Minimize = function (left, right) {
  4091. var min = left.clone();
  4092. min.minimizeInPlace(right);
  4093. return min;
  4094. };
  4095. Vector4.Maximize = function (left, right) {
  4096. var max = left.clone();
  4097. max.maximizeInPlace(right);
  4098. return max;
  4099. };
  4100. /**
  4101. * Returns the distance (float) between the vectors "value1" and "value2".
  4102. */
  4103. Vector4.Distance = function (value1, value2) {
  4104. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4105. };
  4106. /**
  4107. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4108. */
  4109. Vector4.DistanceSquared = function (value1, value2) {
  4110. var x = value1.x - value2.x;
  4111. var y = value1.y - value2.y;
  4112. var z = value1.z - value2.z;
  4113. var w = value1.w - value2.w;
  4114. return (x * x) + (y * y) + (z * z) + (w * w);
  4115. };
  4116. /**
  4117. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4118. */
  4119. Vector4.Center = function (value1, value2) {
  4120. var center = value1.add(value2);
  4121. center.scaleInPlace(0.5);
  4122. return center;
  4123. };
  4124. /**
  4125. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4126. * This methods computes transformed normalized direction vectors only.
  4127. */
  4128. Vector4.TransformNormal = function (vector, transformation) {
  4129. var result = Vector4.Zero();
  4130. Vector4.TransformNormalToRef(vector, transformation, result);
  4131. return result;
  4132. };
  4133. /**
  4134. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4135. * This methods computes transformed normalized direction vectors only.
  4136. */
  4137. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4138. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4139. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4140. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4141. result.x = x;
  4142. result.y = y;
  4143. result.z = z;
  4144. result.w = vector.w;
  4145. };
  4146. /**
  4147. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4148. * This methods computes transformed normalized direction vectors only.
  4149. */
  4150. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4151. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4152. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4153. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4154. result.w = w;
  4155. };
  4156. return Vector4;
  4157. }());
  4158. BABYLON.Vector4 = Vector4;
  4159. var Size = /** @class */ (function () {
  4160. /**
  4161. * Creates a Size object from the passed width and height (floats).
  4162. */
  4163. function Size(width, height) {
  4164. this.width = width;
  4165. this.height = height;
  4166. }
  4167. // Returns a string with the Size width and height.
  4168. Size.prototype.toString = function () {
  4169. return "{W: " + this.width + ", H: " + this.height + "}";
  4170. };
  4171. /**
  4172. * Returns the string "Size"
  4173. */
  4174. Size.prototype.getClassName = function () {
  4175. return "Size";
  4176. };
  4177. /**
  4178. * Returns the Size hash code.
  4179. */
  4180. Size.prototype.getHashCode = function () {
  4181. var hash = this.width || 0;
  4182. hash = (hash * 397) ^ (this.height || 0);
  4183. return hash;
  4184. };
  4185. /**
  4186. * Updates the current size from the passed one.
  4187. * Returns the updated Size.
  4188. */
  4189. Size.prototype.copyFrom = function (src) {
  4190. this.width = src.width;
  4191. this.height = src.height;
  4192. };
  4193. /**
  4194. * Updates in place the current Size from the passed floats.
  4195. * Returns the updated Size.
  4196. */
  4197. Size.prototype.copyFromFloats = function (width, height) {
  4198. this.width = width;
  4199. this.height = height;
  4200. return this;
  4201. };
  4202. /**
  4203. * Updates in place the current Size from the passed floats.
  4204. * Returns the updated Size.
  4205. */
  4206. Size.prototype.set = function (width, height) {
  4207. return this.copyFromFloats(width, height);
  4208. };
  4209. /**
  4210. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4211. */
  4212. Size.prototype.multiplyByFloats = function (w, h) {
  4213. return new Size(this.width * w, this.height * h);
  4214. };
  4215. /**
  4216. * Returns a new Size copied from the passed one.
  4217. */
  4218. Size.prototype.clone = function () {
  4219. return new Size(this.width, this.height);
  4220. };
  4221. /**
  4222. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4223. */
  4224. Size.prototype.equals = function (other) {
  4225. if (!other) {
  4226. return false;
  4227. }
  4228. return (this.width === other.width) && (this.height === other.height);
  4229. };
  4230. Object.defineProperty(Size.prototype, "surface", {
  4231. /**
  4232. * Returns the surface of the Size : width * height (float).
  4233. */
  4234. get: function () {
  4235. return this.width * this.height;
  4236. },
  4237. enumerable: true,
  4238. configurable: true
  4239. });
  4240. /**
  4241. * Returns a new Size set to (0.0, 0.0)
  4242. */
  4243. Size.Zero = function () {
  4244. return new Size(0.0, 0.0);
  4245. };
  4246. /**
  4247. * Returns a new Size set as the addition result of the current Size and the passed one.
  4248. */
  4249. Size.prototype.add = function (otherSize) {
  4250. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4251. return r;
  4252. };
  4253. /**
  4254. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4255. */
  4256. Size.prototype.subtract = function (otherSize) {
  4257. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4258. return r;
  4259. };
  4260. /**
  4261. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4262. */
  4263. Size.Lerp = function (start, end, amount) {
  4264. var w = start.width + ((end.width - start.width) * amount);
  4265. var h = start.height + ((end.height - start.height) * amount);
  4266. return new Size(w, h);
  4267. };
  4268. return Size;
  4269. }());
  4270. BABYLON.Size = Size;
  4271. var Quaternion = /** @class */ (function () {
  4272. /**
  4273. * Creates a new Quaternion from the passed floats.
  4274. */
  4275. function Quaternion(x, y, z, w) {
  4276. if (x === void 0) { x = 0.0; }
  4277. if (y === void 0) { y = 0.0; }
  4278. if (z === void 0) { z = 0.0; }
  4279. if (w === void 0) { w = 1.0; }
  4280. this.x = x;
  4281. this.y = y;
  4282. this.z = z;
  4283. this.w = w;
  4284. }
  4285. /**
  4286. * Returns a string with the Quaternion coordinates.
  4287. */
  4288. Quaternion.prototype.toString = function () {
  4289. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4290. };
  4291. /**
  4292. * Returns the string "Quaternion".
  4293. */
  4294. Quaternion.prototype.getClassName = function () {
  4295. return "Quaternion";
  4296. };
  4297. /**
  4298. * Returns the Quaternion hash code.
  4299. */
  4300. Quaternion.prototype.getHashCode = function () {
  4301. var hash = this.x || 0;
  4302. hash = (hash * 397) ^ (this.y || 0);
  4303. hash = (hash * 397) ^ (this.z || 0);
  4304. hash = (hash * 397) ^ (this.w || 0);
  4305. return hash;
  4306. };
  4307. /**
  4308. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4309. */
  4310. Quaternion.prototype.asArray = function () {
  4311. return [this.x, this.y, this.z, this.w];
  4312. };
  4313. /**
  4314. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4315. */
  4316. Quaternion.prototype.equals = function (otherQuaternion) {
  4317. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4318. };
  4319. /**
  4320. * Returns a new Quaternion copied from the current one.
  4321. */
  4322. Quaternion.prototype.clone = function () {
  4323. return new Quaternion(this.x, this.y, this.z, this.w);
  4324. };
  4325. /**
  4326. * Updates the current Quaternion from the passed one coordinates.
  4327. * Returns the updated Quaterion.
  4328. */
  4329. Quaternion.prototype.copyFrom = function (other) {
  4330. this.x = other.x;
  4331. this.y = other.y;
  4332. this.z = other.z;
  4333. this.w = other.w;
  4334. return this;
  4335. };
  4336. /**
  4337. * Updates the current Quaternion from the passed float coordinates.
  4338. * Returns the updated Quaterion.
  4339. */
  4340. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4341. this.x = x;
  4342. this.y = y;
  4343. this.z = z;
  4344. this.w = w;
  4345. return this;
  4346. };
  4347. /**
  4348. * Updates the current Quaternion from the passed float coordinates.
  4349. * Returns the updated Quaterion.
  4350. */
  4351. Quaternion.prototype.set = function (x, y, z, w) {
  4352. return this.copyFromFloats(x, y, z, w);
  4353. };
  4354. /**
  4355. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4356. */
  4357. Quaternion.prototype.add = function (other) {
  4358. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4359. };
  4360. /**
  4361. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4362. */
  4363. Quaternion.prototype.subtract = function (other) {
  4364. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4365. };
  4366. /**
  4367. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4368. */
  4369. Quaternion.prototype.scale = function (value) {
  4370. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4371. };
  4372. /**
  4373. * Scale the current Quaternion values by a factor to a given Quaternion
  4374. * @param scale defines the scale factor
  4375. * @param result defines the Quaternion object where to store the result
  4376. * @returns the unmodified current Quaternion
  4377. */
  4378. Quaternion.prototype.scaleToRef = function (scale, result) {
  4379. result.x = this.x * scale;
  4380. result.y = this.y * scale;
  4381. result.z = this.z * scale;
  4382. result.w = this.w * scale;
  4383. return this;
  4384. };
  4385. /**
  4386. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4387. * @param scale defines the scale factor
  4388. * @param result defines the Quaternion object where to store the result
  4389. * @returns the unmodified current Quaternion
  4390. */
  4391. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4392. result.x += this.x * scale;
  4393. result.y += this.y * scale;
  4394. result.z += this.z * scale;
  4395. result.w += this.w * scale;
  4396. return this;
  4397. };
  4398. /**
  4399. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4400. */
  4401. Quaternion.prototype.multiply = function (q1) {
  4402. var result = new Quaternion(0, 0, 0, 1.0);
  4403. this.multiplyToRef(q1, result);
  4404. return result;
  4405. };
  4406. /**
  4407. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4408. * Returns the current Quaternion.
  4409. */
  4410. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4411. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4412. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4413. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4414. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4415. result.copyFromFloats(x, y, z, w);
  4416. return this;
  4417. };
  4418. /**
  4419. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4420. * Returns the updated Quaternion.
  4421. */
  4422. Quaternion.prototype.multiplyInPlace = function (q1) {
  4423. this.multiplyToRef(q1, this);
  4424. return this;
  4425. };
  4426. /**
  4427. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4428. * Returns the current Quaternion.
  4429. */
  4430. Quaternion.prototype.conjugateToRef = function (ref) {
  4431. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4432. return this;
  4433. };
  4434. /**
  4435. * Conjugates in place the current Quaternion.
  4436. * Returns the updated Quaternion.
  4437. */
  4438. Quaternion.prototype.conjugateInPlace = function () {
  4439. this.x *= -1;
  4440. this.y *= -1;
  4441. this.z *= -1;
  4442. return this;
  4443. };
  4444. /**
  4445. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4446. */
  4447. Quaternion.prototype.conjugate = function () {
  4448. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4449. return result;
  4450. };
  4451. /**
  4452. * Returns the Quaternion length (float).
  4453. */
  4454. Quaternion.prototype.length = function () {
  4455. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4456. };
  4457. /**
  4458. * Normalize in place the current Quaternion.
  4459. * Returns the updated Quaternion.
  4460. */
  4461. Quaternion.prototype.normalize = function () {
  4462. var length = 1.0 / this.length();
  4463. this.x *= length;
  4464. this.y *= length;
  4465. this.z *= length;
  4466. this.w *= length;
  4467. return this;
  4468. };
  4469. /**
  4470. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4471. * @param order is a reserved parameter and is ignore for now
  4472. * @returns the new Vector3
  4473. */
  4474. Quaternion.prototype.toEulerAngles = function (order) {
  4475. if (order === void 0) { order = "YZX"; }
  4476. var result = Vector3.Zero();
  4477. this.toEulerAnglesToRef(result, order);
  4478. return result;
  4479. };
  4480. /**
  4481. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4482. * @param result defines the vector which will be filled with the Euler angles
  4483. * @param order is a reserved parameter and is ignore for now
  4484. * @returns the current Quaternion
  4485. */
  4486. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4487. if (order === void 0) { order = "YZX"; }
  4488. var qz = this.z;
  4489. var qx = this.x;
  4490. var qy = this.y;
  4491. var qw = this.w;
  4492. var sqw = qw * qw;
  4493. var sqz = qz * qz;
  4494. var sqx = qx * qx;
  4495. var sqy = qy * qy;
  4496. var zAxisY = qy * qz - qx * qw;
  4497. var limit = .4999999;
  4498. if (zAxisY < -limit) {
  4499. result.y = 2 * Math.atan2(qy, qw);
  4500. result.x = Math.PI / 2;
  4501. result.z = 0;
  4502. }
  4503. else if (zAxisY > limit) {
  4504. result.y = 2 * Math.atan2(qy, qw);
  4505. result.x = -Math.PI / 2;
  4506. result.z = 0;
  4507. }
  4508. else {
  4509. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4510. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4511. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4512. }
  4513. return this;
  4514. };
  4515. /**
  4516. * Updates the passed rotation matrix with the current Quaternion values.
  4517. * Returns the current Quaternion.
  4518. */
  4519. Quaternion.prototype.toRotationMatrix = function (result) {
  4520. var xx = this.x * this.x;
  4521. var yy = this.y * this.y;
  4522. var zz = this.z * this.z;
  4523. var xy = this.x * this.y;
  4524. var zw = this.z * this.w;
  4525. var zx = this.z * this.x;
  4526. var yw = this.y * this.w;
  4527. var yz = this.y * this.z;
  4528. var xw = this.x * this.w;
  4529. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4530. result.m[1] = 2.0 * (xy + zw);
  4531. result.m[2] = 2.0 * (zx - yw);
  4532. result.m[3] = 0;
  4533. result.m[4] = 2.0 * (xy - zw);
  4534. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4535. result.m[6] = 2.0 * (yz + xw);
  4536. result.m[7] = 0;
  4537. result.m[8] = 2.0 * (zx + yw);
  4538. result.m[9] = 2.0 * (yz - xw);
  4539. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4540. result.m[11] = 0;
  4541. result.m[12] = 0;
  4542. result.m[13] = 0;
  4543. result.m[14] = 0;
  4544. result.m[15] = 1.0;
  4545. result._markAsUpdated();
  4546. return this;
  4547. };
  4548. /**
  4549. * Updates the current Quaternion from the passed rotation matrix values.
  4550. * Returns the updated Quaternion.
  4551. */
  4552. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4553. Quaternion.FromRotationMatrixToRef(matrix, this);
  4554. return this;
  4555. };
  4556. // Statics
  4557. /**
  4558. * Returns a new Quaternion set from the passed rotation matrix values.
  4559. */
  4560. Quaternion.FromRotationMatrix = function (matrix) {
  4561. var result = new Quaternion();
  4562. Quaternion.FromRotationMatrixToRef(matrix, result);
  4563. return result;
  4564. };
  4565. /**
  4566. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4567. */
  4568. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4569. var data = matrix.m;
  4570. var m11 = data[0], m12 = data[4], m13 = data[8];
  4571. var m21 = data[1], m22 = data[5], m23 = data[9];
  4572. var m31 = data[2], m32 = data[6], m33 = data[10];
  4573. var trace = m11 + m22 + m33;
  4574. var s;
  4575. if (trace > 0) {
  4576. s = 0.5 / Math.sqrt(trace + 1.0);
  4577. result.w = 0.25 / s;
  4578. result.x = (m32 - m23) * s;
  4579. result.y = (m13 - m31) * s;
  4580. result.z = (m21 - m12) * s;
  4581. }
  4582. else if (m11 > m22 && m11 > m33) {
  4583. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4584. result.w = (m32 - m23) / s;
  4585. result.x = 0.25 * s;
  4586. result.y = (m12 + m21) / s;
  4587. result.z = (m13 + m31) / s;
  4588. }
  4589. else if (m22 > m33) {
  4590. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4591. result.w = (m13 - m31) / s;
  4592. result.x = (m12 + m21) / s;
  4593. result.y = 0.25 * s;
  4594. result.z = (m23 + m32) / s;
  4595. }
  4596. else {
  4597. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4598. result.w = (m21 - m12) / s;
  4599. result.x = (m13 + m31) / s;
  4600. result.y = (m23 + m32) / s;
  4601. result.z = 0.25 * s;
  4602. }
  4603. };
  4604. /**
  4605. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4606. */
  4607. Quaternion.Zero = function () {
  4608. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4609. };
  4610. /**
  4611. * Returns a new Quaternion as the inverted current Quaternion.
  4612. */
  4613. Quaternion.Inverse = function (q) {
  4614. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4615. };
  4616. /**
  4617. * Returns the identity Quaternion.
  4618. */
  4619. Quaternion.Identity = function () {
  4620. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4621. };
  4622. Quaternion.IsIdentity = function (quaternion) {
  4623. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4624. };
  4625. /**
  4626. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4627. */
  4628. Quaternion.RotationAxis = function (axis, angle) {
  4629. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4630. };
  4631. /**
  4632. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4633. */
  4634. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4635. var sin = Math.sin(angle / 2);
  4636. axis.normalize();
  4637. result.w = Math.cos(angle / 2);
  4638. result.x = axis.x * sin;
  4639. result.y = axis.y * sin;
  4640. result.z = axis.z * sin;
  4641. return result;
  4642. };
  4643. /**
  4644. * Retuns a new Quaternion set from the starting index of the passed array.
  4645. */
  4646. Quaternion.FromArray = function (array, offset) {
  4647. if (!offset) {
  4648. offset = 0;
  4649. }
  4650. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4651. };
  4652. /**
  4653. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4654. */
  4655. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4656. var q = new Quaternion();
  4657. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4658. return q;
  4659. };
  4660. /**
  4661. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4662. */
  4663. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4664. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4665. var halfRoll = roll * 0.5;
  4666. var halfPitch = pitch * 0.5;
  4667. var halfYaw = yaw * 0.5;
  4668. var sinRoll = Math.sin(halfRoll);
  4669. var cosRoll = Math.cos(halfRoll);
  4670. var sinPitch = Math.sin(halfPitch);
  4671. var cosPitch = Math.cos(halfPitch);
  4672. var sinYaw = Math.sin(halfYaw);
  4673. var cosYaw = Math.cos(halfYaw);
  4674. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4675. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4676. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4677. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4678. };
  4679. /**
  4680. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4681. */
  4682. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4683. var result = new Quaternion();
  4684. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4685. return result;
  4686. };
  4687. /**
  4688. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4689. */
  4690. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4691. // Produces a quaternion from Euler angles in the z-x-z orientation
  4692. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4693. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4694. var halfBeta = beta * 0.5;
  4695. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4696. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4697. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4698. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4699. };
  4700. /**
  4701. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4702. * cf to Vector3.RotationFromAxis() documentation.
  4703. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4704. */
  4705. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4706. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4707. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4708. return quat;
  4709. };
  4710. /**
  4711. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4712. * cf to Vector3.RotationFromAxis() documentation.
  4713. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4714. */
  4715. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4716. var rotMat = MathTmp.Matrix[0];
  4717. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4718. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4719. };
  4720. Quaternion.Slerp = function (left, right, amount) {
  4721. var result = Quaternion.Identity();
  4722. Quaternion.SlerpToRef(left, right, amount, result);
  4723. return result;
  4724. };
  4725. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4726. var num2;
  4727. var num3;
  4728. var num = amount;
  4729. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4730. var flag = false;
  4731. if (num4 < 0) {
  4732. flag = true;
  4733. num4 = -num4;
  4734. }
  4735. if (num4 > 0.999999) {
  4736. num3 = 1 - num;
  4737. num2 = flag ? -num : num;
  4738. }
  4739. else {
  4740. var num5 = Math.acos(num4);
  4741. var num6 = (1.0 / Math.sin(num5));
  4742. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4743. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4744. }
  4745. result.x = (num3 * left.x) + (num2 * right.x);
  4746. result.y = (num3 * left.y) + (num2 * right.y);
  4747. result.z = (num3 * left.z) + (num2 * right.z);
  4748. result.w = (num3 * left.w) + (num2 * right.w);
  4749. };
  4750. /**
  4751. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4752. */
  4753. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4754. var squared = amount * amount;
  4755. var cubed = amount * squared;
  4756. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4757. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4758. var part3 = (cubed - (2.0 * squared)) + amount;
  4759. var part4 = cubed - squared;
  4760. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4761. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4762. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4763. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4764. return new Quaternion(x, y, z, w);
  4765. };
  4766. return Quaternion;
  4767. }());
  4768. BABYLON.Quaternion = Quaternion;
  4769. var Matrix = /** @class */ (function () {
  4770. function Matrix() {
  4771. this._isIdentity = false;
  4772. this._isIdentityDirty = true;
  4773. this.m = new Float32Array(16);
  4774. this._markAsUpdated();
  4775. }
  4776. Matrix.prototype._markAsUpdated = function () {
  4777. this.updateFlag = Matrix._updateFlagSeed++;
  4778. this._isIdentityDirty = true;
  4779. };
  4780. // Properties
  4781. /**
  4782. * Boolean : True is the matrix is the identity matrix
  4783. */
  4784. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4785. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4786. if (this._isIdentityDirty) {
  4787. this._isIdentityDirty = false;
  4788. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4789. this._isIdentity = false;
  4790. }
  4791. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4792. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4793. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4794. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4795. this._isIdentity = false;
  4796. }
  4797. else {
  4798. this._isIdentity = true;
  4799. }
  4800. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4801. this._isIdentity = false;
  4802. }
  4803. }
  4804. return this._isIdentity;
  4805. };
  4806. /**
  4807. * Returns the matrix determinant (float).
  4808. */
  4809. Matrix.prototype.determinant = function () {
  4810. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4811. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4812. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4813. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4814. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4815. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4816. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4817. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4818. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4819. };
  4820. // Methods
  4821. /**
  4822. * Returns the matrix underlying array.
  4823. */
  4824. Matrix.prototype.toArray = function () {
  4825. return this.m;
  4826. };
  4827. /**
  4828. * Returns the matrix underlying array.
  4829. */
  4830. Matrix.prototype.asArray = function () {
  4831. return this.toArray();
  4832. };
  4833. /**
  4834. * Inverts in place the Matrix.
  4835. * Returns the Matrix inverted.
  4836. */
  4837. Matrix.prototype.invert = function () {
  4838. this.invertToRef(this);
  4839. return this;
  4840. };
  4841. /**
  4842. * Sets all the matrix elements to zero.
  4843. * Returns the Matrix.
  4844. */
  4845. Matrix.prototype.reset = function () {
  4846. for (var index = 0; index < 16; index++) {
  4847. this.m[index] = 0.0;
  4848. }
  4849. this._markAsUpdated();
  4850. return this;
  4851. };
  4852. /**
  4853. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4854. */
  4855. Matrix.prototype.add = function (other) {
  4856. var result = new Matrix();
  4857. this.addToRef(other, result);
  4858. return result;
  4859. };
  4860. /**
  4861. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4862. * Returns the Matrix.
  4863. */
  4864. Matrix.prototype.addToRef = function (other, result) {
  4865. for (var index = 0; index < 16; index++) {
  4866. result.m[index] = this.m[index] + other.m[index];
  4867. }
  4868. result._markAsUpdated();
  4869. return this;
  4870. };
  4871. /**
  4872. * Adds in place the passed matrix to the current Matrix.
  4873. * Returns the updated Matrix.
  4874. */
  4875. Matrix.prototype.addToSelf = function (other) {
  4876. for (var index = 0; index < 16; index++) {
  4877. this.m[index] += other.m[index];
  4878. }
  4879. this._markAsUpdated();
  4880. return this;
  4881. };
  4882. /**
  4883. * Sets the passed matrix with the current inverted Matrix.
  4884. * Returns the unmodified current Matrix.
  4885. */
  4886. Matrix.prototype.invertToRef = function (other) {
  4887. var l1 = this.m[0];
  4888. var l2 = this.m[1];
  4889. var l3 = this.m[2];
  4890. var l4 = this.m[3];
  4891. var l5 = this.m[4];
  4892. var l6 = this.m[5];
  4893. var l7 = this.m[6];
  4894. var l8 = this.m[7];
  4895. var l9 = this.m[8];
  4896. var l10 = this.m[9];
  4897. var l11 = this.m[10];
  4898. var l12 = this.m[11];
  4899. var l13 = this.m[12];
  4900. var l14 = this.m[13];
  4901. var l15 = this.m[14];
  4902. var l16 = this.m[15];
  4903. var l17 = (l11 * l16) - (l12 * l15);
  4904. var l18 = (l10 * l16) - (l12 * l14);
  4905. var l19 = (l10 * l15) - (l11 * l14);
  4906. var l20 = (l9 * l16) - (l12 * l13);
  4907. var l21 = (l9 * l15) - (l11 * l13);
  4908. var l22 = (l9 * l14) - (l10 * l13);
  4909. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4910. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4911. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4912. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4913. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4914. var l28 = (l7 * l16) - (l8 * l15);
  4915. var l29 = (l6 * l16) - (l8 * l14);
  4916. var l30 = (l6 * l15) - (l7 * l14);
  4917. var l31 = (l5 * l16) - (l8 * l13);
  4918. var l32 = (l5 * l15) - (l7 * l13);
  4919. var l33 = (l5 * l14) - (l6 * l13);
  4920. var l34 = (l7 * l12) - (l8 * l11);
  4921. var l35 = (l6 * l12) - (l8 * l10);
  4922. var l36 = (l6 * l11) - (l7 * l10);
  4923. var l37 = (l5 * l12) - (l8 * l9);
  4924. var l38 = (l5 * l11) - (l7 * l9);
  4925. var l39 = (l5 * l10) - (l6 * l9);
  4926. other.m[0] = l23 * l27;
  4927. other.m[4] = l24 * l27;
  4928. other.m[8] = l25 * l27;
  4929. other.m[12] = l26 * l27;
  4930. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4931. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4932. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4933. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4934. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4935. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4936. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4937. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4938. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4939. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4940. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4941. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4942. other._markAsUpdated();
  4943. return this;
  4944. };
  4945. /**
  4946. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4947. * Returns the updated Matrix.
  4948. */
  4949. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4950. this.m[12] = x;
  4951. this.m[13] = y;
  4952. this.m[14] = z;
  4953. this._markAsUpdated();
  4954. return this;
  4955. };
  4956. /**
  4957. * Inserts the translation vector in the current Matrix.
  4958. * Returns the updated Matrix.
  4959. */
  4960. Matrix.prototype.setTranslation = function (vector3) {
  4961. this.m[12] = vector3.x;
  4962. this.m[13] = vector3.y;
  4963. this.m[14] = vector3.z;
  4964. this._markAsUpdated();
  4965. return this;
  4966. };
  4967. /**
  4968. * Returns a new Vector3 as the extracted translation from the Matrix.
  4969. */
  4970. Matrix.prototype.getTranslation = function () {
  4971. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4972. };
  4973. /**
  4974. * Fill a Vector3 with the extracted translation from the Matrix.
  4975. */
  4976. Matrix.prototype.getTranslationToRef = function (result) {
  4977. result.x = this.m[12];
  4978. result.y = this.m[13];
  4979. result.z = this.m[14];
  4980. return this;
  4981. };
  4982. /**
  4983. * Remove rotation and scaling part from the Matrix.
  4984. * Returns the updated Matrix.
  4985. */
  4986. Matrix.prototype.removeRotationAndScaling = function () {
  4987. this.setRowFromFloats(0, 1, 0, 0, 0);
  4988. this.setRowFromFloats(1, 0, 1, 0, 0);
  4989. this.setRowFromFloats(2, 0, 0, 1, 0);
  4990. return this;
  4991. };
  4992. /**
  4993. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4994. */
  4995. Matrix.prototype.multiply = function (other) {
  4996. var result = new Matrix();
  4997. this.multiplyToRef(other, result);
  4998. return result;
  4999. };
  5000. /**
  5001. * Updates the current Matrix from the passed one values.
  5002. * Returns the updated Matrix.
  5003. */
  5004. Matrix.prototype.copyFrom = function (other) {
  5005. for (var index = 0; index < 16; index++) {
  5006. this.m[index] = other.m[index];
  5007. }
  5008. this._markAsUpdated();
  5009. return this;
  5010. };
  5011. /**
  5012. * Populates the passed array from the starting index with the Matrix values.
  5013. * Returns the Matrix.
  5014. */
  5015. Matrix.prototype.copyToArray = function (array, offset) {
  5016. if (offset === void 0) { offset = 0; }
  5017. for (var index = 0; index < 16; index++) {
  5018. array[offset + index] = this.m[index];
  5019. }
  5020. return this;
  5021. };
  5022. /**
  5023. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5024. */
  5025. Matrix.prototype.multiplyToRef = function (other, result) {
  5026. this.multiplyToArray(other, result.m, 0);
  5027. result._markAsUpdated();
  5028. return this;
  5029. };
  5030. /**
  5031. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5032. */
  5033. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5034. var tm0 = this.m[0];
  5035. var tm1 = this.m[1];
  5036. var tm2 = this.m[2];
  5037. var tm3 = this.m[3];
  5038. var tm4 = this.m[4];
  5039. var tm5 = this.m[5];
  5040. var tm6 = this.m[6];
  5041. var tm7 = this.m[7];
  5042. var tm8 = this.m[8];
  5043. var tm9 = this.m[9];
  5044. var tm10 = this.m[10];
  5045. var tm11 = this.m[11];
  5046. var tm12 = this.m[12];
  5047. var tm13 = this.m[13];
  5048. var tm14 = this.m[14];
  5049. var tm15 = this.m[15];
  5050. var om0 = other.m[0];
  5051. var om1 = other.m[1];
  5052. var om2 = other.m[2];
  5053. var om3 = other.m[3];
  5054. var om4 = other.m[4];
  5055. var om5 = other.m[5];
  5056. var om6 = other.m[6];
  5057. var om7 = other.m[7];
  5058. var om8 = other.m[8];
  5059. var om9 = other.m[9];
  5060. var om10 = other.m[10];
  5061. var om11 = other.m[11];
  5062. var om12 = other.m[12];
  5063. var om13 = other.m[13];
  5064. var om14 = other.m[14];
  5065. var om15 = other.m[15];
  5066. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5067. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5068. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5069. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5070. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5071. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5072. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5073. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5074. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5075. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5076. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5077. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5078. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5079. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5080. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5081. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5082. return this;
  5083. };
  5084. /**
  5085. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5086. */
  5087. Matrix.prototype.equals = function (value) {
  5088. return value &&
  5089. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5090. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5091. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5092. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5093. };
  5094. /**
  5095. * Returns a new Matrix from the current Matrix.
  5096. */
  5097. Matrix.prototype.clone = function () {
  5098. 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]);
  5099. };
  5100. /**
  5101. * Returns the string "Matrix"
  5102. */
  5103. Matrix.prototype.getClassName = function () {
  5104. return "Matrix";
  5105. };
  5106. /**
  5107. * Returns the Matrix hash code.
  5108. */
  5109. Matrix.prototype.getHashCode = function () {
  5110. var hash = this.m[0] || 0;
  5111. for (var i = 1; i < 16; i++) {
  5112. hash = (hash * 397) ^ (this.m[i] || 0);
  5113. }
  5114. return hash;
  5115. };
  5116. /**
  5117. * Decomposes the current Matrix into :
  5118. * - a scale vector3 passed as a reference to update,
  5119. * - a rotation quaternion passed as a reference to update,
  5120. * - a translation vector3 passed as a reference to update.
  5121. * Returns the true if operation was successful.
  5122. */
  5123. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5124. translation.x = this.m[12];
  5125. translation.y = this.m[13];
  5126. translation.z = this.m[14];
  5127. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5128. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5129. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5130. if (this.determinant() <= 0) {
  5131. scale.y *= -1;
  5132. }
  5133. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5134. rotation.x = 0;
  5135. rotation.y = 0;
  5136. rotation.z = 0;
  5137. rotation.w = 1;
  5138. return false;
  5139. }
  5140. 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]);
  5141. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5142. return true;
  5143. };
  5144. /**
  5145. * Returns the index-th row of the current matrix as a new Vector4.
  5146. */
  5147. Matrix.prototype.getRow = function (index) {
  5148. if (index < 0 || index > 3) {
  5149. return null;
  5150. }
  5151. var i = index * 4;
  5152. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5153. };
  5154. /**
  5155. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5156. * Returns the updated Matrix.
  5157. */
  5158. Matrix.prototype.setRow = function (index, row) {
  5159. if (index < 0 || index > 3) {
  5160. return this;
  5161. }
  5162. var i = index * 4;
  5163. this.m[i + 0] = row.x;
  5164. this.m[i + 1] = row.y;
  5165. this.m[i + 2] = row.z;
  5166. this.m[i + 3] = row.w;
  5167. this._markAsUpdated();
  5168. return this;
  5169. };
  5170. /**
  5171. * Compute the transpose of the matrix.
  5172. * Returns a new Matrix.
  5173. */
  5174. Matrix.prototype.transpose = function () {
  5175. return Matrix.Transpose(this);
  5176. };
  5177. /**
  5178. * Compute the transpose of the matrix.
  5179. * Returns the current matrix.
  5180. */
  5181. Matrix.prototype.transposeToRef = function (result) {
  5182. Matrix.TransposeToRef(this, result);
  5183. return this;
  5184. };
  5185. /**
  5186. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5187. * Returns the updated Matrix.
  5188. */
  5189. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5190. if (index < 0 || index > 3) {
  5191. return this;
  5192. }
  5193. var i = index * 4;
  5194. this.m[i + 0] = x;
  5195. this.m[i + 1] = y;
  5196. this.m[i + 2] = z;
  5197. this.m[i + 3] = w;
  5198. this._markAsUpdated();
  5199. return this;
  5200. };
  5201. /**
  5202. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5203. * @param scale defines the scale factor
  5204. * @returns a new Matrix
  5205. */
  5206. Matrix.prototype.scale = function (scale) {
  5207. var result = new Matrix();
  5208. this.scaleToRef(scale, result);
  5209. return result;
  5210. };
  5211. /**
  5212. * Scale the current Matrix values by a factor to a given result Matrix
  5213. * @param scale defines the scale factor
  5214. * @param result defines the Matrix to store the result
  5215. * @returns the current Matrix
  5216. */
  5217. Matrix.prototype.scaleToRef = function (scale, result) {
  5218. for (var index = 0; index < 16; index++) {
  5219. result.m[index] = this.m[index] * scale;
  5220. }
  5221. result._markAsUpdated();
  5222. return this;
  5223. };
  5224. /**
  5225. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5226. * @param scale defines the scale factor
  5227. * @param result defines the Matrix to store the result
  5228. * @returns the current Matrix
  5229. */
  5230. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5231. for (var index = 0; index < 16; index++) {
  5232. result.m[index] += this.m[index] * scale;
  5233. }
  5234. result._markAsUpdated();
  5235. return this;
  5236. };
  5237. /**
  5238. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5239. * @param ref matrix to store the result
  5240. */
  5241. Matrix.prototype.toNormalMatrix = function (ref) {
  5242. this.invertToRef(ref);
  5243. ref.transpose();
  5244. var m = ref.m;
  5245. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5246. };
  5247. /**
  5248. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5249. */
  5250. Matrix.prototype.getRotationMatrix = function () {
  5251. var result = Matrix.Identity();
  5252. this.getRotationMatrixToRef(result);
  5253. return result;
  5254. };
  5255. /**
  5256. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5257. * Returns the current Matrix.
  5258. */
  5259. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5260. var m = this.m;
  5261. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5262. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5263. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5264. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5265. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5266. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5267. 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);
  5268. return this;
  5269. };
  5270. // Statics
  5271. /**
  5272. * Returns a new Matrix set from the starting index of the passed array.
  5273. */
  5274. Matrix.FromArray = function (array, offset) {
  5275. var result = new Matrix();
  5276. if (!offset) {
  5277. offset = 0;
  5278. }
  5279. Matrix.FromArrayToRef(array, offset, result);
  5280. return result;
  5281. };
  5282. /**
  5283. * Sets the passed "result" matrix from the starting index of the passed array.
  5284. */
  5285. Matrix.FromArrayToRef = function (array, offset, result) {
  5286. for (var index = 0; index < 16; index++) {
  5287. result.m[index] = array[index + offset];
  5288. }
  5289. result._markAsUpdated();
  5290. };
  5291. /**
  5292. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5293. */
  5294. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5295. for (var index = 0; index < 16; index++) {
  5296. result.m[index] = array[index + offset] * scale;
  5297. }
  5298. result._markAsUpdated();
  5299. };
  5300. /**
  5301. * Sets the passed matrix "result" with the 16 passed floats.
  5302. */
  5303. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5304. result.m[0] = initialM11;
  5305. result.m[1] = initialM12;
  5306. result.m[2] = initialM13;
  5307. result.m[3] = initialM14;
  5308. result.m[4] = initialM21;
  5309. result.m[5] = initialM22;
  5310. result.m[6] = initialM23;
  5311. result.m[7] = initialM24;
  5312. result.m[8] = initialM31;
  5313. result.m[9] = initialM32;
  5314. result.m[10] = initialM33;
  5315. result.m[11] = initialM34;
  5316. result.m[12] = initialM41;
  5317. result.m[13] = initialM42;
  5318. result.m[14] = initialM43;
  5319. result.m[15] = initialM44;
  5320. result._markAsUpdated();
  5321. };
  5322. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5323. /**
  5324. * Static identity matrix to be used as readonly matrix
  5325. * Must not be updated.
  5326. */
  5327. get: function () {
  5328. return Matrix._identityReadOnly;
  5329. },
  5330. enumerable: true,
  5331. configurable: true
  5332. });
  5333. /**
  5334. * Returns a new Matrix set from the 16 passed floats.
  5335. */
  5336. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5337. var result = new Matrix();
  5338. result.m[0] = initialM11;
  5339. result.m[1] = initialM12;
  5340. result.m[2] = initialM13;
  5341. result.m[3] = initialM14;
  5342. result.m[4] = initialM21;
  5343. result.m[5] = initialM22;
  5344. result.m[6] = initialM23;
  5345. result.m[7] = initialM24;
  5346. result.m[8] = initialM31;
  5347. result.m[9] = initialM32;
  5348. result.m[10] = initialM33;
  5349. result.m[11] = initialM34;
  5350. result.m[12] = initialM41;
  5351. result.m[13] = initialM42;
  5352. result.m[14] = initialM43;
  5353. result.m[15] = initialM44;
  5354. return result;
  5355. };
  5356. /**
  5357. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5358. */
  5359. Matrix.Compose = function (scale, rotation, translation) {
  5360. var result = Matrix.Identity();
  5361. Matrix.ComposeToRef(scale, rotation, translation, result);
  5362. return result;
  5363. };
  5364. /**
  5365. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5366. */
  5367. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5368. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5369. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5370. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5371. result.setTranslation(translation);
  5372. };
  5373. /**
  5374. * Returns a new indentity Matrix.
  5375. */
  5376. Matrix.Identity = function () {
  5377. 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);
  5378. };
  5379. /**
  5380. * Sets the passed "result" as an identity matrix.
  5381. */
  5382. Matrix.IdentityToRef = function (result) {
  5383. 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);
  5384. };
  5385. /**
  5386. * Returns a new zero Matrix.
  5387. */
  5388. Matrix.Zero = function () {
  5389. 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);
  5390. };
  5391. /**
  5392. * Returns a new rotation matrix for "angle" radians around the X axis.
  5393. */
  5394. Matrix.RotationX = function (angle) {
  5395. var result = new Matrix();
  5396. Matrix.RotationXToRef(angle, result);
  5397. return result;
  5398. };
  5399. /**
  5400. * Returns a new Matrix as the passed inverted one.
  5401. */
  5402. Matrix.Invert = function (source) {
  5403. var result = new Matrix();
  5404. source.invertToRef(result);
  5405. return result;
  5406. };
  5407. /**
  5408. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5409. */
  5410. Matrix.RotationXToRef = function (angle, result) {
  5411. var s = Math.sin(angle);
  5412. var c = Math.cos(angle);
  5413. result.m[0] = 1.0;
  5414. result.m[15] = 1.0;
  5415. result.m[5] = c;
  5416. result.m[10] = c;
  5417. result.m[9] = -s;
  5418. result.m[6] = s;
  5419. result.m[1] = 0.0;
  5420. result.m[2] = 0.0;
  5421. result.m[3] = 0.0;
  5422. result.m[4] = 0.0;
  5423. result.m[7] = 0.0;
  5424. result.m[8] = 0.0;
  5425. result.m[11] = 0.0;
  5426. result.m[12] = 0.0;
  5427. result.m[13] = 0.0;
  5428. result.m[14] = 0.0;
  5429. result._markAsUpdated();
  5430. };
  5431. /**
  5432. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5433. */
  5434. Matrix.RotationY = function (angle) {
  5435. var result = new Matrix();
  5436. Matrix.RotationYToRef(angle, result);
  5437. return result;
  5438. };
  5439. /**
  5440. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5441. */
  5442. Matrix.RotationYToRef = function (angle, result) {
  5443. var s = Math.sin(angle);
  5444. var c = Math.cos(angle);
  5445. result.m[5] = 1.0;
  5446. result.m[15] = 1.0;
  5447. result.m[0] = c;
  5448. result.m[2] = -s;
  5449. result.m[8] = s;
  5450. result.m[10] = c;
  5451. result.m[1] = 0.0;
  5452. result.m[3] = 0.0;
  5453. result.m[4] = 0.0;
  5454. result.m[6] = 0.0;
  5455. result.m[7] = 0.0;
  5456. result.m[9] = 0.0;
  5457. result.m[11] = 0.0;
  5458. result.m[12] = 0.0;
  5459. result.m[13] = 0.0;
  5460. result.m[14] = 0.0;
  5461. result._markAsUpdated();
  5462. };
  5463. /**
  5464. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5465. */
  5466. Matrix.RotationZ = function (angle) {
  5467. var result = new Matrix();
  5468. Matrix.RotationZToRef(angle, result);
  5469. return result;
  5470. };
  5471. /**
  5472. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5473. */
  5474. Matrix.RotationZToRef = function (angle, result) {
  5475. var s = Math.sin(angle);
  5476. var c = Math.cos(angle);
  5477. result.m[10] = 1.0;
  5478. result.m[15] = 1.0;
  5479. result.m[0] = c;
  5480. result.m[1] = s;
  5481. result.m[4] = -s;
  5482. result.m[5] = c;
  5483. result.m[2] = 0.0;
  5484. result.m[3] = 0.0;
  5485. result.m[6] = 0.0;
  5486. result.m[7] = 0.0;
  5487. result.m[8] = 0.0;
  5488. result.m[9] = 0.0;
  5489. result.m[11] = 0.0;
  5490. result.m[12] = 0.0;
  5491. result.m[13] = 0.0;
  5492. result.m[14] = 0.0;
  5493. result._markAsUpdated();
  5494. };
  5495. /**
  5496. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5497. */
  5498. Matrix.RotationAxis = function (axis, angle) {
  5499. var result = Matrix.Zero();
  5500. Matrix.RotationAxisToRef(axis, angle, result);
  5501. return result;
  5502. };
  5503. /**
  5504. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5505. */
  5506. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5507. var s = Math.sin(-angle);
  5508. var c = Math.cos(-angle);
  5509. var c1 = 1 - c;
  5510. axis.normalize();
  5511. result.m[0] = (axis.x * axis.x) * c1 + c;
  5512. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5513. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5514. result.m[3] = 0.0;
  5515. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5516. result.m[5] = (axis.y * axis.y) * c1 + c;
  5517. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5518. result.m[7] = 0.0;
  5519. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5520. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5521. result.m[10] = (axis.z * axis.z) * c1 + c;
  5522. result.m[11] = 0.0;
  5523. result.m[15] = 1.0;
  5524. result._markAsUpdated();
  5525. };
  5526. /**
  5527. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5528. */
  5529. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5530. var result = new Matrix();
  5531. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5532. return result;
  5533. };
  5534. /**
  5535. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5536. */
  5537. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5538. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5539. this._tempQuaternion.toRotationMatrix(result);
  5540. };
  5541. /**
  5542. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5543. */
  5544. Matrix.Scaling = function (x, y, z) {
  5545. var result = Matrix.Zero();
  5546. Matrix.ScalingToRef(x, y, z, result);
  5547. return result;
  5548. };
  5549. /**
  5550. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5551. */
  5552. Matrix.ScalingToRef = function (x, y, z, result) {
  5553. result.m[0] = x;
  5554. result.m[1] = 0.0;
  5555. result.m[2] = 0.0;
  5556. result.m[3] = 0.0;
  5557. result.m[4] = 0.0;
  5558. result.m[5] = y;
  5559. result.m[6] = 0.0;
  5560. result.m[7] = 0.0;
  5561. result.m[8] = 0.0;
  5562. result.m[9] = 0.0;
  5563. result.m[10] = z;
  5564. result.m[11] = 0.0;
  5565. result.m[12] = 0.0;
  5566. result.m[13] = 0.0;
  5567. result.m[14] = 0.0;
  5568. result.m[15] = 1.0;
  5569. result._markAsUpdated();
  5570. };
  5571. /**
  5572. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5573. */
  5574. Matrix.Translation = function (x, y, z) {
  5575. var result = Matrix.Identity();
  5576. Matrix.TranslationToRef(x, y, z, result);
  5577. return result;
  5578. };
  5579. /**
  5580. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5581. */
  5582. Matrix.TranslationToRef = function (x, y, z, result) {
  5583. 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);
  5584. };
  5585. /**
  5586. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5587. * @param startValue defines the start value
  5588. * @param endValue defines the end value
  5589. * @param gradient defines the gradient factor
  5590. * @returns the new matrix
  5591. */
  5592. Matrix.Lerp = function (startValue, endValue, gradient) {
  5593. var result = Matrix.Zero();
  5594. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5595. return result;
  5596. };
  5597. /**
  5598. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5599. * @param startValue defines the start value
  5600. * @param endValue defines the end value
  5601. * @param gradient defines the gradient factor
  5602. * @param result defines the Matrix object where to store data
  5603. */
  5604. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5605. for (var index = 0; index < 16; index++) {
  5606. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5607. }
  5608. result._markAsUpdated();
  5609. };
  5610. /**
  5611. * Returns a new Matrix whose values are computed by :
  5612. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5613. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5614. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5615. */
  5616. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5617. var startScale = new Vector3(0, 0, 0);
  5618. var startRotation = new Quaternion();
  5619. var startTranslation = new Vector3(0, 0, 0);
  5620. startValue.decompose(startScale, startRotation, startTranslation);
  5621. var endScale = new Vector3(0, 0, 0);
  5622. var endRotation = new Quaternion();
  5623. var endTranslation = new Vector3(0, 0, 0);
  5624. endValue.decompose(endScale, endRotation, endTranslation);
  5625. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5626. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5627. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5628. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5629. };
  5630. /**
  5631. * 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".
  5632. * This methods works for a Left-Handed system.
  5633. */
  5634. Matrix.LookAtLH = function (eye, target, up) {
  5635. var result = Matrix.Zero();
  5636. Matrix.LookAtLHToRef(eye, target, up, result);
  5637. return result;
  5638. };
  5639. /**
  5640. * 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".
  5641. * This methods works for a Left-Handed system.
  5642. */
  5643. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5644. // Z axis
  5645. target.subtractToRef(eye, this._zAxis);
  5646. this._zAxis.normalize();
  5647. // X axis
  5648. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5649. if (this._xAxis.lengthSquared() === 0) {
  5650. this._xAxis.x = 1.0;
  5651. }
  5652. else {
  5653. this._xAxis.normalize();
  5654. }
  5655. // Y axis
  5656. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5657. this._yAxis.normalize();
  5658. // Eye angles
  5659. var ex = -Vector3.Dot(this._xAxis, eye);
  5660. var ey = -Vector3.Dot(this._yAxis, eye);
  5661. var ez = -Vector3.Dot(this._zAxis, eye);
  5662. 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);
  5663. };
  5664. /**
  5665. * 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".
  5666. * This methods works for a Right-Handed system.
  5667. */
  5668. Matrix.LookAtRH = function (eye, target, up) {
  5669. var result = Matrix.Zero();
  5670. Matrix.LookAtRHToRef(eye, target, up, result);
  5671. return result;
  5672. };
  5673. /**
  5674. * 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".
  5675. * This methods works for a Left-Handed system.
  5676. */
  5677. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5678. // Z axis
  5679. eye.subtractToRef(target, this._zAxis);
  5680. this._zAxis.normalize();
  5681. // X axis
  5682. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5683. if (this._xAxis.lengthSquared() === 0) {
  5684. this._xAxis.x = 1.0;
  5685. }
  5686. else {
  5687. this._xAxis.normalize();
  5688. }
  5689. // Y axis
  5690. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5691. this._yAxis.normalize();
  5692. // Eye angles
  5693. var ex = -Vector3.Dot(this._xAxis, eye);
  5694. var ey = -Vector3.Dot(this._yAxis, eye);
  5695. var ez = -Vector3.Dot(this._zAxis, eye);
  5696. 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);
  5697. };
  5698. /**
  5699. * 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.
  5700. */
  5701. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5702. var matrix = Matrix.Zero();
  5703. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5704. return matrix;
  5705. };
  5706. /**
  5707. * 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.
  5708. */
  5709. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5710. var n = znear;
  5711. var f = zfar;
  5712. var a = 2.0 / width;
  5713. var b = 2.0 / height;
  5714. var c = 2.0 / (f - n);
  5715. var d = -(f + n) / (f - n);
  5716. 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);
  5717. };
  5718. /**
  5719. * 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.
  5720. */
  5721. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5722. var matrix = Matrix.Zero();
  5723. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5724. return matrix;
  5725. };
  5726. /**
  5727. * 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.
  5728. */
  5729. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5730. var n = znear;
  5731. var f = zfar;
  5732. var a = 2.0 / (right - left);
  5733. var b = 2.0 / (top - bottom);
  5734. var c = 2.0 / (f - n);
  5735. var d = -(f + n) / (f - n);
  5736. var i0 = (left + right) / (left - right);
  5737. var i1 = (top + bottom) / (bottom - top);
  5738. 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);
  5739. };
  5740. /**
  5741. * 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.
  5742. */
  5743. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5744. var matrix = Matrix.Zero();
  5745. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5746. return matrix;
  5747. };
  5748. /**
  5749. * 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.
  5750. */
  5751. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5752. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5753. result.m[10] *= -1.0;
  5754. };
  5755. /**
  5756. * 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.
  5757. */
  5758. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5759. var matrix = Matrix.Zero();
  5760. var n = znear;
  5761. var f = zfar;
  5762. var a = 2.0 * n / width;
  5763. var b = 2.0 * n / height;
  5764. var c = (f + n) / (f - n);
  5765. var d = -2.0 * f * n / (f - n);
  5766. 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);
  5767. return matrix;
  5768. };
  5769. /**
  5770. * 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.
  5771. */
  5772. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5773. var matrix = Matrix.Zero();
  5774. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5775. return matrix;
  5776. };
  5777. /**
  5778. * 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.
  5779. */
  5780. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5781. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5782. var n = znear;
  5783. var f = zfar;
  5784. var t = 1.0 / (Math.tan(fov * 0.5));
  5785. var a = isVerticalFovFixed ? (t / aspect) : t;
  5786. var b = isVerticalFovFixed ? t : (t * aspect);
  5787. var c = (f + n) / (f - n);
  5788. var d = -2.0 * f * n / (f - n);
  5789. 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);
  5790. };
  5791. /**
  5792. * 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.
  5793. */
  5794. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5795. var matrix = Matrix.Zero();
  5796. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5797. return matrix;
  5798. };
  5799. /**
  5800. * 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.
  5801. */
  5802. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5803. //alternatively this could be expressed as:
  5804. // m = PerspectiveFovLHToRef
  5805. // m[10] *= -1.0;
  5806. // m[11] *= -1.0;
  5807. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5808. var n = znear;
  5809. var f = zfar;
  5810. var t = 1.0 / (Math.tan(fov * 0.5));
  5811. var a = isVerticalFovFixed ? (t / aspect) : t;
  5812. var b = isVerticalFovFixed ? t : (t * aspect);
  5813. var c = -(f + n) / (f - n);
  5814. var d = -2 * f * n / (f - n);
  5815. 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);
  5816. };
  5817. /**
  5818. * 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.
  5819. */
  5820. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5821. if (rightHanded === void 0) { rightHanded = false; }
  5822. var rightHandedFactor = rightHanded ? -1 : 1;
  5823. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5824. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5825. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5826. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5827. var xScale = 2.0 / (leftTan + rightTan);
  5828. var yScale = 2.0 / (upTan + downTan);
  5829. result.m[0] = xScale;
  5830. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5831. result.m[5] = yScale;
  5832. result.m[6] = result.m[7] = 0.0;
  5833. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5834. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5835. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5836. result.m[10] = -zfar / (znear - zfar);
  5837. result.m[11] = 1.0 * rightHandedFactor;
  5838. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5839. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5840. // result.m[14] = (znear * zfar) / (znear - zfar);
  5841. result._markAsUpdated();
  5842. };
  5843. /**
  5844. * Returns the final transformation matrix : world * view * projection * viewport
  5845. */
  5846. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5847. var cw = viewport.width;
  5848. var ch = viewport.height;
  5849. var cx = viewport.x;
  5850. var cy = viewport.y;
  5851. 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);
  5852. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5853. };
  5854. /**
  5855. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5856. */
  5857. Matrix.GetAsMatrix2x2 = function (matrix) {
  5858. return new Float32Array([
  5859. matrix.m[0], matrix.m[1],
  5860. matrix.m[4], matrix.m[5]
  5861. ]);
  5862. };
  5863. /**
  5864. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5865. */
  5866. Matrix.GetAsMatrix3x3 = function (matrix) {
  5867. return new Float32Array([
  5868. matrix.m[0], matrix.m[1], matrix.m[2],
  5869. matrix.m[4], matrix.m[5], matrix.m[6],
  5870. matrix.m[8], matrix.m[9], matrix.m[10]
  5871. ]);
  5872. };
  5873. /**
  5874. * Compute the transpose of the passed Matrix.
  5875. * Returns a new Matrix.
  5876. */
  5877. Matrix.Transpose = function (matrix) {
  5878. var result = new Matrix();
  5879. Matrix.TransposeToRef(matrix, result);
  5880. return result;
  5881. };
  5882. /**
  5883. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5884. */
  5885. Matrix.TransposeToRef = function (matrix, result) {
  5886. result.m[0] = matrix.m[0];
  5887. result.m[1] = matrix.m[4];
  5888. result.m[2] = matrix.m[8];
  5889. result.m[3] = matrix.m[12];
  5890. result.m[4] = matrix.m[1];
  5891. result.m[5] = matrix.m[5];
  5892. result.m[6] = matrix.m[9];
  5893. result.m[7] = matrix.m[13];
  5894. result.m[8] = matrix.m[2];
  5895. result.m[9] = matrix.m[6];
  5896. result.m[10] = matrix.m[10];
  5897. result.m[11] = matrix.m[14];
  5898. result.m[12] = matrix.m[3];
  5899. result.m[13] = matrix.m[7];
  5900. result.m[14] = matrix.m[11];
  5901. result.m[15] = matrix.m[15];
  5902. };
  5903. /**
  5904. * Returns a new Matrix as the reflection matrix across the passed plane.
  5905. */
  5906. Matrix.Reflection = function (plane) {
  5907. var matrix = new Matrix();
  5908. Matrix.ReflectionToRef(plane, matrix);
  5909. return matrix;
  5910. };
  5911. /**
  5912. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5913. */
  5914. Matrix.ReflectionToRef = function (plane, result) {
  5915. plane.normalize();
  5916. var x = plane.normal.x;
  5917. var y = plane.normal.y;
  5918. var z = plane.normal.z;
  5919. var temp = -2 * x;
  5920. var temp2 = -2 * y;
  5921. var temp3 = -2 * z;
  5922. result.m[0] = (temp * x) + 1;
  5923. result.m[1] = temp2 * x;
  5924. result.m[2] = temp3 * x;
  5925. result.m[3] = 0.0;
  5926. result.m[4] = temp * y;
  5927. result.m[5] = (temp2 * y) + 1;
  5928. result.m[6] = temp3 * y;
  5929. result.m[7] = 0.0;
  5930. result.m[8] = temp * z;
  5931. result.m[9] = temp2 * z;
  5932. result.m[10] = (temp3 * z) + 1;
  5933. result.m[11] = 0.0;
  5934. result.m[12] = temp * plane.d;
  5935. result.m[13] = temp2 * plane.d;
  5936. result.m[14] = temp3 * plane.d;
  5937. result.m[15] = 1.0;
  5938. result._markAsUpdated();
  5939. };
  5940. /**
  5941. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5942. */
  5943. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5944. result.m[0] = xaxis.x;
  5945. result.m[1] = xaxis.y;
  5946. result.m[2] = xaxis.z;
  5947. result.m[3] = 0.0;
  5948. result.m[4] = yaxis.x;
  5949. result.m[5] = yaxis.y;
  5950. result.m[6] = yaxis.z;
  5951. result.m[7] = 0.0;
  5952. result.m[8] = zaxis.x;
  5953. result.m[9] = zaxis.y;
  5954. result.m[10] = zaxis.z;
  5955. result.m[11] = 0.0;
  5956. result.m[12] = 0.0;
  5957. result.m[13] = 0.0;
  5958. result.m[14] = 0.0;
  5959. result.m[15] = 1.0;
  5960. result._markAsUpdated();
  5961. };
  5962. /**
  5963. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5964. */
  5965. Matrix.FromQuaternionToRef = function (quat, result) {
  5966. var xx = quat.x * quat.x;
  5967. var yy = quat.y * quat.y;
  5968. var zz = quat.z * quat.z;
  5969. var xy = quat.x * quat.y;
  5970. var zw = quat.z * quat.w;
  5971. var zx = quat.z * quat.x;
  5972. var yw = quat.y * quat.w;
  5973. var yz = quat.y * quat.z;
  5974. var xw = quat.x * quat.w;
  5975. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5976. result.m[1] = 2.0 * (xy + zw);
  5977. result.m[2] = 2.0 * (zx - yw);
  5978. result.m[3] = 0.0;
  5979. result.m[4] = 2.0 * (xy - zw);
  5980. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5981. result.m[6] = 2.0 * (yz + xw);
  5982. result.m[7] = 0.0;
  5983. result.m[8] = 2.0 * (zx + yw);
  5984. result.m[9] = 2.0 * (yz - xw);
  5985. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5986. result.m[11] = 0.0;
  5987. result.m[12] = 0.0;
  5988. result.m[13] = 0.0;
  5989. result.m[14] = 0.0;
  5990. result.m[15] = 1.0;
  5991. result._markAsUpdated();
  5992. };
  5993. Matrix._tempQuaternion = new Quaternion();
  5994. Matrix._xAxis = Vector3.Zero();
  5995. Matrix._yAxis = Vector3.Zero();
  5996. Matrix._zAxis = Vector3.Zero();
  5997. Matrix._updateFlagSeed = 0;
  5998. Matrix._identityReadOnly = Matrix.Identity();
  5999. return Matrix;
  6000. }());
  6001. BABYLON.Matrix = Matrix;
  6002. var Plane = /** @class */ (function () {
  6003. /**
  6004. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6005. */
  6006. function Plane(a, b, c, d) {
  6007. this.normal = new Vector3(a, b, c);
  6008. this.d = d;
  6009. }
  6010. /**
  6011. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6012. */
  6013. Plane.prototype.asArray = function () {
  6014. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6015. };
  6016. // Methods
  6017. /**
  6018. * Returns a new plane copied from the current Plane.
  6019. */
  6020. Plane.prototype.clone = function () {
  6021. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6022. };
  6023. /**
  6024. * Returns the string "Plane".
  6025. */
  6026. Plane.prototype.getClassName = function () {
  6027. return "Plane";
  6028. };
  6029. /**
  6030. * Returns the Plane hash code.
  6031. */
  6032. Plane.prototype.getHashCode = function () {
  6033. var hash = this.normal.getHashCode();
  6034. hash = (hash * 397) ^ (this.d || 0);
  6035. return hash;
  6036. };
  6037. /**
  6038. * Normalize the current Plane in place.
  6039. * Returns the updated Plane.
  6040. */
  6041. Plane.prototype.normalize = function () {
  6042. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6043. var magnitude = 0.0;
  6044. if (norm !== 0) {
  6045. magnitude = 1.0 / norm;
  6046. }
  6047. this.normal.x *= magnitude;
  6048. this.normal.y *= magnitude;
  6049. this.normal.z *= magnitude;
  6050. this.d *= magnitude;
  6051. return this;
  6052. };
  6053. /**
  6054. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6055. */
  6056. Plane.prototype.transform = function (transformation) {
  6057. var transposedMatrix = Matrix.Transpose(transformation);
  6058. var x = this.normal.x;
  6059. var y = this.normal.y;
  6060. var z = this.normal.z;
  6061. var d = this.d;
  6062. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6063. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6064. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6065. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6066. return new Plane(normalX, normalY, normalZ, finalD);
  6067. };
  6068. /**
  6069. * Returns the dot product (float) of the point coordinates and the plane normal.
  6070. */
  6071. Plane.prototype.dotCoordinate = function (point) {
  6072. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6073. };
  6074. /**
  6075. * Updates the current Plane from the plane defined by the three passed points.
  6076. * Returns the updated Plane.
  6077. */
  6078. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6079. var x1 = point2.x - point1.x;
  6080. var y1 = point2.y - point1.y;
  6081. var z1 = point2.z - point1.z;
  6082. var x2 = point3.x - point1.x;
  6083. var y2 = point3.y - point1.y;
  6084. var z2 = point3.z - point1.z;
  6085. var yz = (y1 * z2) - (z1 * y2);
  6086. var xz = (z1 * x2) - (x1 * z2);
  6087. var xy = (x1 * y2) - (y1 * x2);
  6088. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6089. var invPyth;
  6090. if (pyth !== 0) {
  6091. invPyth = 1.0 / pyth;
  6092. }
  6093. else {
  6094. invPyth = 0.0;
  6095. }
  6096. this.normal.x = yz * invPyth;
  6097. this.normal.y = xz * invPyth;
  6098. this.normal.z = xy * invPyth;
  6099. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6100. return this;
  6101. };
  6102. /**
  6103. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6104. */
  6105. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6106. var dot = Vector3.Dot(this.normal, direction);
  6107. return (dot <= epsilon);
  6108. };
  6109. /**
  6110. * Returns the signed distance (float) from the passed point to the Plane.
  6111. */
  6112. Plane.prototype.signedDistanceTo = function (point) {
  6113. return Vector3.Dot(point, this.normal) + this.d;
  6114. };
  6115. // Statics
  6116. /**
  6117. * Returns a new Plane from the passed array.
  6118. */
  6119. Plane.FromArray = function (array) {
  6120. return new Plane(array[0], array[1], array[2], array[3]);
  6121. };
  6122. /**
  6123. * Returns a new Plane defined by the three passed points.
  6124. */
  6125. Plane.FromPoints = function (point1, point2, point3) {
  6126. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6127. result.copyFromPoints(point1, point2, point3);
  6128. return result;
  6129. };
  6130. /**
  6131. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6132. * Note : the vector "normal" is updated because normalized.
  6133. */
  6134. Plane.FromPositionAndNormal = function (origin, normal) {
  6135. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6136. normal.normalize();
  6137. result.normal = normal;
  6138. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6139. return result;
  6140. };
  6141. /**
  6142. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6143. */
  6144. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6145. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6146. return Vector3.Dot(point, normal) + d;
  6147. };
  6148. return Plane;
  6149. }());
  6150. BABYLON.Plane = Plane;
  6151. var Viewport = /** @class */ (function () {
  6152. /**
  6153. * Creates a Viewport object located at (x, y) and sized (width, height).
  6154. */
  6155. function Viewport(x, y, width, height) {
  6156. this.x = x;
  6157. this.y = y;
  6158. this.width = width;
  6159. this.height = height;
  6160. }
  6161. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6162. if (renderWidthOrEngine.getRenderWidth) {
  6163. var engine = renderWidthOrEngine;
  6164. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6165. }
  6166. var renderWidth = renderWidthOrEngine;
  6167. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6168. };
  6169. /**
  6170. * Returns a new Viewport copied from the current one.
  6171. */
  6172. Viewport.prototype.clone = function () {
  6173. return new Viewport(this.x, this.y, this.width, this.height);
  6174. };
  6175. return Viewport;
  6176. }());
  6177. BABYLON.Viewport = Viewport;
  6178. var Frustum = /** @class */ (function () {
  6179. function Frustum() {
  6180. }
  6181. /**
  6182. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6183. */
  6184. Frustum.GetPlanes = function (transform) {
  6185. var frustumPlanes = [];
  6186. for (var index = 0; index < 6; index++) {
  6187. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6188. }
  6189. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6190. return frustumPlanes;
  6191. };
  6192. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6193. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6194. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6195. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6196. frustumPlane.d = transform.m[15] + transform.m[14];
  6197. frustumPlane.normalize();
  6198. };
  6199. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6200. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6201. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6202. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6203. frustumPlane.d = transform.m[15] - transform.m[14];
  6204. frustumPlane.normalize();
  6205. };
  6206. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6207. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6208. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6209. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6210. frustumPlane.d = transform.m[15] + transform.m[12];
  6211. frustumPlane.normalize();
  6212. };
  6213. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6214. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6215. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6216. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6217. frustumPlane.d = transform.m[15] - transform.m[12];
  6218. frustumPlane.normalize();
  6219. };
  6220. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6221. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6222. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6223. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6224. frustumPlane.d = transform.m[15] - transform.m[13];
  6225. frustumPlane.normalize();
  6226. };
  6227. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6228. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6229. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6230. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6231. frustumPlane.d = transform.m[15] + transform.m[13];
  6232. frustumPlane.normalize();
  6233. };
  6234. /**
  6235. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6236. */
  6237. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6238. // Near
  6239. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6240. // Far
  6241. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6242. // Left
  6243. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6244. // Right
  6245. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6246. // Top
  6247. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6248. // Bottom
  6249. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6250. };
  6251. return Frustum;
  6252. }());
  6253. BABYLON.Frustum = Frustum;
  6254. var Space;
  6255. (function (Space) {
  6256. Space[Space["LOCAL"] = 0] = "LOCAL";
  6257. Space[Space["WORLD"] = 1] = "WORLD";
  6258. Space[Space["BONE"] = 2] = "BONE";
  6259. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6260. var Axis = /** @class */ (function () {
  6261. function Axis() {
  6262. }
  6263. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6264. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6265. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6266. return Axis;
  6267. }());
  6268. BABYLON.Axis = Axis;
  6269. ;
  6270. var BezierCurve = /** @class */ (function () {
  6271. function BezierCurve() {
  6272. }
  6273. /**
  6274. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6275. */
  6276. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6277. // Extract X (which is equal to time here)
  6278. var f0 = 1 - 3 * x2 + 3 * x1;
  6279. var f1 = 3 * x2 - 6 * x1;
  6280. var f2 = 3 * x1;
  6281. var refinedT = t;
  6282. for (var i = 0; i < 5; i++) {
  6283. var refinedT2 = refinedT * refinedT;
  6284. var refinedT3 = refinedT2 * refinedT;
  6285. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6286. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6287. refinedT -= (x - t) * slope;
  6288. refinedT = Math.min(1, Math.max(0, refinedT));
  6289. }
  6290. // Resolve cubic bezier for the given x
  6291. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6292. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6293. Math.pow(refinedT, 3);
  6294. };
  6295. return BezierCurve;
  6296. }());
  6297. BABYLON.BezierCurve = BezierCurve;
  6298. var Orientation;
  6299. (function (Orientation) {
  6300. Orientation[Orientation["CW"] = 0] = "CW";
  6301. Orientation[Orientation["CCW"] = 1] = "CCW";
  6302. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6303. var Angle = /** @class */ (function () {
  6304. /**
  6305. * Creates an Angle object of "radians" radians (float).
  6306. */
  6307. function Angle(radians) {
  6308. var _this = this;
  6309. /**
  6310. * Returns the Angle value in degrees (float).
  6311. */
  6312. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6313. /**
  6314. * Returns the Angle value in radians (float).
  6315. */
  6316. this.radians = function () { return _this._radians; };
  6317. this._radians = radians;
  6318. if (this._radians < 0.0)
  6319. this._radians += (2.0 * Math.PI);
  6320. }
  6321. /**
  6322. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6323. */
  6324. Angle.BetweenTwoPoints = function (a, b) {
  6325. var delta = b.subtract(a);
  6326. var theta = Math.atan2(delta.y, delta.x);
  6327. return new Angle(theta);
  6328. };
  6329. /**
  6330. * Returns a new Angle object from the passed float in radians.
  6331. */
  6332. Angle.FromRadians = function (radians) {
  6333. return new Angle(radians);
  6334. };
  6335. /**
  6336. * Returns a new Angle object from the passed float in degrees.
  6337. */
  6338. Angle.FromDegrees = function (degrees) {
  6339. return new Angle(degrees * Math.PI / 180.0);
  6340. };
  6341. return Angle;
  6342. }());
  6343. BABYLON.Angle = Angle;
  6344. var Arc2 = /** @class */ (function () {
  6345. /**
  6346. * Creates an Arc object from the three passed points : start, middle and end.
  6347. */
  6348. function Arc2(startPoint, midPoint, endPoint) {
  6349. this.startPoint = startPoint;
  6350. this.midPoint = midPoint;
  6351. this.endPoint = endPoint;
  6352. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6353. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6354. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6355. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6356. 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);
  6357. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6358. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6359. var a1 = this.startAngle.degrees();
  6360. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6361. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6362. // angles correction
  6363. if (a2 - a1 > +180.0)
  6364. a2 -= 360.0;
  6365. if (a2 - a1 < -180.0)
  6366. a2 += 360.0;
  6367. if (a3 - a2 > +180.0)
  6368. a3 -= 360.0;
  6369. if (a3 - a2 < -180.0)
  6370. a3 += 360.0;
  6371. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6372. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6373. }
  6374. return Arc2;
  6375. }());
  6376. BABYLON.Arc2 = Arc2;
  6377. var Path2 = /** @class */ (function () {
  6378. /**
  6379. * Creates a Path2 object from the starting 2D coordinates x and y.
  6380. */
  6381. function Path2(x, y) {
  6382. this._points = new Array();
  6383. this._length = 0.0;
  6384. this.closed = false;
  6385. this._points.push(new Vector2(x, y));
  6386. }
  6387. /**
  6388. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6389. * Returns the updated Path2.
  6390. */
  6391. Path2.prototype.addLineTo = function (x, y) {
  6392. if (this.closed) {
  6393. return this;
  6394. }
  6395. var newPoint = new Vector2(x, y);
  6396. var previousPoint = this._points[this._points.length - 1];
  6397. this._points.push(newPoint);
  6398. this._length += newPoint.subtract(previousPoint).length();
  6399. return this;
  6400. };
  6401. /**
  6402. * 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.
  6403. * Returns the updated Path2.
  6404. */
  6405. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6406. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6407. if (this.closed) {
  6408. return this;
  6409. }
  6410. var startPoint = this._points[this._points.length - 1];
  6411. var midPoint = new Vector2(midX, midY);
  6412. var endPoint = new Vector2(endX, endY);
  6413. var arc = new Arc2(startPoint, midPoint, endPoint);
  6414. var increment = arc.angle.radians() / numberOfSegments;
  6415. if (arc.orientation === Orientation.CW)
  6416. increment *= -1;
  6417. var currentAngle = arc.startAngle.radians() + increment;
  6418. for (var i = 0; i < numberOfSegments; i++) {
  6419. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6420. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6421. this.addLineTo(x, y);
  6422. currentAngle += increment;
  6423. }
  6424. return this;
  6425. };
  6426. /**
  6427. * Closes the Path2.
  6428. * Returns the Path2.
  6429. */
  6430. Path2.prototype.close = function () {
  6431. this.closed = true;
  6432. return this;
  6433. };
  6434. /**
  6435. * Returns the Path2 total length (float).
  6436. */
  6437. Path2.prototype.length = function () {
  6438. var result = this._length;
  6439. if (!this.closed) {
  6440. var lastPoint = this._points[this._points.length - 1];
  6441. var firstPoint = this._points[0];
  6442. result += (firstPoint.subtract(lastPoint).length());
  6443. }
  6444. return result;
  6445. };
  6446. /**
  6447. * Returns the Path2 internal array of points.
  6448. */
  6449. Path2.prototype.getPoints = function () {
  6450. return this._points;
  6451. };
  6452. /**
  6453. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6454. */
  6455. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6456. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6457. return Vector2.Zero();
  6458. }
  6459. var lengthPosition = normalizedLengthPosition * this.length();
  6460. var previousOffset = 0;
  6461. for (var i = 0; i < this._points.length; i++) {
  6462. var j = (i + 1) % this._points.length;
  6463. var a = this._points[i];
  6464. var b = this._points[j];
  6465. var bToA = b.subtract(a);
  6466. var nextOffset = (bToA.length() + previousOffset);
  6467. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6468. var dir = bToA.normalize();
  6469. var localOffset = lengthPosition - previousOffset;
  6470. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6471. }
  6472. previousOffset = nextOffset;
  6473. }
  6474. return Vector2.Zero();
  6475. };
  6476. /**
  6477. * Returns a new Path2 starting at the coordinates (x, y).
  6478. */
  6479. Path2.StartingAt = function (x, y) {
  6480. return new Path2(x, y);
  6481. };
  6482. return Path2;
  6483. }());
  6484. BABYLON.Path2 = Path2;
  6485. var Path3D = /** @class */ (function () {
  6486. /**
  6487. * new Path3D(path, normal, raw)
  6488. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6489. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6490. * path : an array of Vector3, the curve axis of the Path3D
  6491. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6492. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6493. */
  6494. function Path3D(path, firstNormal, raw) {
  6495. if (firstNormal === void 0) { firstNormal = null; }
  6496. this.path = path;
  6497. this._curve = new Array();
  6498. this._distances = new Array();
  6499. this._tangents = new Array();
  6500. this._normals = new Array();
  6501. this._binormals = new Array();
  6502. for (var p = 0; p < path.length; p++) {
  6503. this._curve[p] = path[p].clone(); // hard copy
  6504. }
  6505. this._raw = raw || false;
  6506. this._compute(firstNormal);
  6507. }
  6508. /**
  6509. * Returns the Path3D array of successive Vector3 designing its curve.
  6510. */
  6511. Path3D.prototype.getCurve = function () {
  6512. return this._curve;
  6513. };
  6514. /**
  6515. * Returns an array populated with tangent vectors on each Path3D curve point.
  6516. */
  6517. Path3D.prototype.getTangents = function () {
  6518. return this._tangents;
  6519. };
  6520. /**
  6521. * Returns an array populated with normal vectors on each Path3D curve point.
  6522. */
  6523. Path3D.prototype.getNormals = function () {
  6524. return this._normals;
  6525. };
  6526. /**
  6527. * Returns an array populated with binormal vectors on each Path3D curve point.
  6528. */
  6529. Path3D.prototype.getBinormals = function () {
  6530. return this._binormals;
  6531. };
  6532. /**
  6533. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6534. */
  6535. Path3D.prototype.getDistances = function () {
  6536. return this._distances;
  6537. };
  6538. /**
  6539. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6540. * Returns the same object updated.
  6541. */
  6542. Path3D.prototype.update = function (path, firstNormal) {
  6543. if (firstNormal === void 0) { firstNormal = null; }
  6544. for (var p = 0; p < path.length; p++) {
  6545. this._curve[p].x = path[p].x;
  6546. this._curve[p].y = path[p].y;
  6547. this._curve[p].z = path[p].z;
  6548. }
  6549. this._compute(firstNormal);
  6550. return this;
  6551. };
  6552. // private function compute() : computes tangents, normals and binormals
  6553. Path3D.prototype._compute = function (firstNormal) {
  6554. var l = this._curve.length;
  6555. // first and last tangents
  6556. this._tangents[0] = this._getFirstNonNullVector(0);
  6557. if (!this._raw) {
  6558. this._tangents[0].normalize();
  6559. }
  6560. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6561. if (!this._raw) {
  6562. this._tangents[l - 1].normalize();
  6563. }
  6564. // normals and binormals at first point : arbitrary vector with _normalVector()
  6565. var tg0 = this._tangents[0];
  6566. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6567. this._normals[0] = pp0;
  6568. if (!this._raw) {
  6569. this._normals[0].normalize();
  6570. }
  6571. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6572. if (!this._raw) {
  6573. this._binormals[0].normalize();
  6574. }
  6575. this._distances[0] = 0.0;
  6576. // normals and binormals : next points
  6577. var prev; // previous vector (segment)
  6578. var cur; // current vector (segment)
  6579. var curTang; // current tangent
  6580. // previous normal
  6581. var prevBinor; // previous binormal
  6582. for (var i = 1; i < l; i++) {
  6583. // tangents
  6584. prev = this._getLastNonNullVector(i);
  6585. if (i < l - 1) {
  6586. cur = this._getFirstNonNullVector(i);
  6587. this._tangents[i] = prev.add(cur);
  6588. this._tangents[i].normalize();
  6589. }
  6590. this._distances[i] = this._distances[i - 1] + prev.length();
  6591. // normals and binormals
  6592. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6593. curTang = this._tangents[i];
  6594. prevBinor = this._binormals[i - 1];
  6595. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6596. if (!this._raw) {
  6597. this._normals[i].normalize();
  6598. }
  6599. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6600. if (!this._raw) {
  6601. this._binormals[i].normalize();
  6602. }
  6603. }
  6604. };
  6605. // private function getFirstNonNullVector(index)
  6606. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6607. Path3D.prototype._getFirstNonNullVector = function (index) {
  6608. var i = 1;
  6609. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6610. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6611. i++;
  6612. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6613. }
  6614. return nNVector;
  6615. };
  6616. // private function getLastNonNullVector(index)
  6617. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6618. Path3D.prototype._getLastNonNullVector = function (index) {
  6619. var i = 1;
  6620. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6621. while (nLVector.length() === 0 && index > i + 1) {
  6622. i++;
  6623. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6624. }
  6625. return nLVector;
  6626. };
  6627. // private function normalVector(v0, vt, va) :
  6628. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6629. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6630. Path3D.prototype._normalVector = function (v0, vt, va) {
  6631. var normal0;
  6632. var tgl = vt.length();
  6633. if (tgl === 0.0) {
  6634. tgl = 1.0;
  6635. }
  6636. if (va === undefined || va === null) {
  6637. var point;
  6638. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6639. point = new Vector3(0.0, -1.0, 0.0);
  6640. }
  6641. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6642. point = new Vector3(1.0, 0.0, 0.0);
  6643. }
  6644. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6645. point = new Vector3(0.0, 0.0, 1.0);
  6646. }
  6647. else {
  6648. point = Vector3.Zero();
  6649. }
  6650. normal0 = Vector3.Cross(vt, point);
  6651. }
  6652. else {
  6653. normal0 = Vector3.Cross(vt, va);
  6654. Vector3.CrossToRef(normal0, vt, normal0);
  6655. }
  6656. normal0.normalize();
  6657. return normal0;
  6658. };
  6659. return Path3D;
  6660. }());
  6661. BABYLON.Path3D = Path3D;
  6662. var Curve3 = /** @class */ (function () {
  6663. /**
  6664. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6665. * A Curve3 is designed from a series of successive Vector3.
  6666. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6667. */
  6668. function Curve3(points) {
  6669. this._length = 0.0;
  6670. this._points = points;
  6671. this._length = this._computeLength(points);
  6672. }
  6673. /**
  6674. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6675. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6676. * @param v1 (Vector3) the control point
  6677. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6678. * @param nbPoints (integer) the wanted number of points in the curve
  6679. */
  6680. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6681. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6682. var bez = new Array();
  6683. var equation = function (t, val0, val1, val2) {
  6684. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6685. return res;
  6686. };
  6687. for (var i = 0; i <= nbPoints; i++) {
  6688. 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)));
  6689. }
  6690. return new Curve3(bez);
  6691. };
  6692. /**
  6693. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6694. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6695. * @param v1 (Vector3) the first control point
  6696. * @param v2 (Vector3) the second control point
  6697. * @param v3 (Vector3) the end point of the Cubic Bezier
  6698. * @param nbPoints (integer) the wanted number of points in the curve
  6699. */
  6700. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6701. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6702. var bez = new Array();
  6703. var equation = function (t, val0, val1, val2, val3) {
  6704. 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;
  6705. return res;
  6706. };
  6707. for (var i = 0; i <= nbPoints; i++) {
  6708. 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)));
  6709. }
  6710. return new Curve3(bez);
  6711. };
  6712. /**
  6713. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6714. * @param p1 (Vector3) the origin point of the Hermite Spline
  6715. * @param t1 (Vector3) the tangent vector at the origin point
  6716. * @param p2 (Vector3) the end point of the Hermite Spline
  6717. * @param t2 (Vector3) the tangent vector at the end point
  6718. * @param nbPoints (integer) the wanted number of points in the curve
  6719. */
  6720. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6721. var hermite = new Array();
  6722. var step = 1.0 / nbPoints;
  6723. for (var i = 0; i <= nbPoints; i++) {
  6724. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6725. }
  6726. return new Curve3(hermite);
  6727. };
  6728. /**
  6729. * Returns a Curve3 object along a CatmullRom Spline curve :
  6730. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6731. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6732. */
  6733. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6734. var totalPoints = new Array();
  6735. totalPoints.push(points[0].clone());
  6736. Array.prototype.push.apply(totalPoints, points);
  6737. totalPoints.push(points[points.length - 1].clone());
  6738. var catmullRom = new Array();
  6739. var step = 1.0 / nbPoints;
  6740. var amount = 0.0;
  6741. for (var i = 0; i < totalPoints.length - 3; i++) {
  6742. amount = 0;
  6743. for (var c = 0; c < nbPoints; c++) {
  6744. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6745. amount += step;
  6746. }
  6747. }
  6748. i--;
  6749. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6750. return new Curve3(catmullRom);
  6751. };
  6752. /**
  6753. * Returns the Curve3 stored array of successive Vector3
  6754. */
  6755. Curve3.prototype.getPoints = function () {
  6756. return this._points;
  6757. };
  6758. /**
  6759. * Returns the computed length (float) of the curve.
  6760. */
  6761. Curve3.prototype.length = function () {
  6762. return this._length;
  6763. };
  6764. /**
  6765. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6766. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6767. * curveA and curveB keep unchanged.
  6768. */
  6769. Curve3.prototype.continue = function (curve) {
  6770. var lastPoint = this._points[this._points.length - 1];
  6771. var continuedPoints = this._points.slice();
  6772. var curvePoints = curve.getPoints();
  6773. for (var i = 1; i < curvePoints.length; i++) {
  6774. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6775. }
  6776. var continuedCurve = new Curve3(continuedPoints);
  6777. return continuedCurve;
  6778. };
  6779. Curve3.prototype._computeLength = function (path) {
  6780. var l = 0;
  6781. for (var i = 1; i < path.length; i++) {
  6782. l += (path[i].subtract(path[i - 1])).length();
  6783. }
  6784. return l;
  6785. };
  6786. return Curve3;
  6787. }());
  6788. BABYLON.Curve3 = Curve3;
  6789. // Vertex formats
  6790. var PositionNormalVertex = /** @class */ (function () {
  6791. function PositionNormalVertex(position, normal) {
  6792. if (position === void 0) { position = Vector3.Zero(); }
  6793. if (normal === void 0) { normal = Vector3.Up(); }
  6794. this.position = position;
  6795. this.normal = normal;
  6796. }
  6797. PositionNormalVertex.prototype.clone = function () {
  6798. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6799. };
  6800. return PositionNormalVertex;
  6801. }());
  6802. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6803. var PositionNormalTextureVertex = /** @class */ (function () {
  6804. function PositionNormalTextureVertex(position, normal, uv) {
  6805. if (position === void 0) { position = Vector3.Zero(); }
  6806. if (normal === void 0) { normal = Vector3.Up(); }
  6807. if (uv === void 0) { uv = Vector2.Zero(); }
  6808. this.position = position;
  6809. this.normal = normal;
  6810. this.uv = uv;
  6811. }
  6812. PositionNormalTextureVertex.prototype.clone = function () {
  6813. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6814. };
  6815. return PositionNormalTextureVertex;
  6816. }());
  6817. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6818. // Temporary pre-allocated objects for engine internal use
  6819. // usage in any internal function :
  6820. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6821. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6822. var Tmp = /** @class */ (function () {
  6823. function Tmp() {
  6824. }
  6825. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6826. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6827. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6828. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6829. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6830. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6831. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6832. Matrix.Zero(), Matrix.Zero(),
  6833. Matrix.Zero(), Matrix.Zero(),
  6834. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6835. return Tmp;
  6836. }());
  6837. BABYLON.Tmp = Tmp;
  6838. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6839. var MathTmp = /** @class */ (function () {
  6840. function MathTmp() {
  6841. }
  6842. MathTmp.Vector3 = [Vector3.Zero()];
  6843. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6844. MathTmp.Quaternion = [Quaternion.Zero()];
  6845. return MathTmp;
  6846. }());
  6847. })(BABYLON || (BABYLON = {}));
  6848. //# sourceMappingURL=babylon.math.js.map
  6849. "use strict";
  6850. var BABYLON;
  6851. (function (BABYLON) {
  6852. var Scalar = /** @class */ (function () {
  6853. function Scalar() {
  6854. }
  6855. /**
  6856. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6857. */
  6858. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6859. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6860. var num = a - b;
  6861. return -epsilon <= num && num <= epsilon;
  6862. };
  6863. /**
  6864. * Returns a string : the upper case translation of the number i to hexadecimal.
  6865. */
  6866. Scalar.ToHex = function (i) {
  6867. var str = i.toString(16);
  6868. if (i <= 15) {
  6869. return ("0" + str).toUpperCase();
  6870. }
  6871. return str.toUpperCase();
  6872. };
  6873. /**
  6874. * Returns -1 if value is negative and +1 is value is positive.
  6875. * Returns the value itself if it's equal to zero.
  6876. */
  6877. Scalar.Sign = function (value) {
  6878. value = +value; // convert to a number
  6879. if (value === 0 || isNaN(value))
  6880. return value;
  6881. return value > 0 ? 1 : -1;
  6882. };
  6883. /**
  6884. * Returns the value itself if it's between min and max.
  6885. * Returns min if the value is lower than min.
  6886. * Returns max if the value is greater than max.
  6887. */
  6888. Scalar.Clamp = function (value, min, max) {
  6889. if (min === void 0) { min = 0; }
  6890. if (max === void 0) { max = 1; }
  6891. return Math.min(max, Math.max(min, value));
  6892. };
  6893. /**
  6894. * Returns the log2 of value.
  6895. */
  6896. Scalar.Log2 = function (value) {
  6897. return Math.log(value) * Math.LOG2E;
  6898. };
  6899. /**
  6900. * Loops the value, so that it is never larger than length and never smaller than 0.
  6901. *
  6902. * This is similar to the modulo operator but it works with floating point numbers.
  6903. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6904. * With t = 5 and length = 2.5, the result would be 0.0.
  6905. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6906. */
  6907. Scalar.Repeat = function (value, length) {
  6908. return value - Math.floor(value / length) * length;
  6909. };
  6910. /**
  6911. * Normalize the value between 0.0 and 1.0 using min and max values
  6912. */
  6913. Scalar.Normalize = function (value, min, max) {
  6914. return (value - min) / (max - min);
  6915. };
  6916. /**
  6917. * Denormalize the value from 0.0 and 1.0 using min and max values
  6918. */
  6919. Scalar.Denormalize = function (normalized, min, max) {
  6920. return (normalized * (max - min) + min);
  6921. };
  6922. /**
  6923. * Calculates the shortest difference between two given angles given in degrees.
  6924. */
  6925. Scalar.DeltaAngle = function (current, target) {
  6926. var num = Scalar.Repeat(target - current, 360.0);
  6927. if (num > 180.0) {
  6928. num -= 360.0;
  6929. }
  6930. return num;
  6931. };
  6932. /**
  6933. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6934. *
  6935. * The returned value will move back and forth between 0 and length
  6936. */
  6937. Scalar.PingPong = function (tx, length) {
  6938. var t = Scalar.Repeat(tx, length * 2.0);
  6939. return length - Math.abs(t - length);
  6940. };
  6941. /**
  6942. * Interpolates between min and max with smoothing at the limits.
  6943. *
  6944. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6945. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6946. */
  6947. Scalar.SmoothStep = function (from, to, tx) {
  6948. var t = Scalar.Clamp(tx);
  6949. t = -2.0 * t * t * t + 3.0 * t * t;
  6950. return to * t + from * (1.0 - t);
  6951. };
  6952. /**
  6953. * Moves a value current towards target.
  6954. *
  6955. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6956. * Negative values of maxDelta pushes the value away from target.
  6957. */
  6958. Scalar.MoveTowards = function (current, target, maxDelta) {
  6959. var result = 0;
  6960. if (Math.abs(target - current) <= maxDelta) {
  6961. result = target;
  6962. }
  6963. else {
  6964. result = current + Scalar.Sign(target - current) * maxDelta;
  6965. }
  6966. return result;
  6967. };
  6968. /**
  6969. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6970. *
  6971. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6972. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6973. */
  6974. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6975. var num = Scalar.DeltaAngle(current, target);
  6976. var result = 0;
  6977. if (-maxDelta < num && num < maxDelta) {
  6978. result = target;
  6979. }
  6980. else {
  6981. target = current + num;
  6982. result = Scalar.MoveTowards(current, target, maxDelta);
  6983. }
  6984. return result;
  6985. };
  6986. /**
  6987. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6988. */
  6989. Scalar.Lerp = function (start, end, amount) {
  6990. return start + ((end - start) * amount);
  6991. };
  6992. /**
  6993. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6994. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6995. */
  6996. Scalar.LerpAngle = function (start, end, amount) {
  6997. var num = Scalar.Repeat(end - start, 360.0);
  6998. if (num > 180.0) {
  6999. num -= 360.0;
  7000. }
  7001. return start + num * Scalar.Clamp(amount);
  7002. };
  7003. /**
  7004. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7005. */
  7006. Scalar.InverseLerp = function (a, b, value) {
  7007. var result = 0;
  7008. if (a != b) {
  7009. result = Scalar.Clamp((value - a) / (b - a));
  7010. }
  7011. else {
  7012. result = 0.0;
  7013. }
  7014. return result;
  7015. };
  7016. /**
  7017. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7018. */
  7019. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7020. var squared = amount * amount;
  7021. var cubed = amount * squared;
  7022. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7023. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7024. var part3 = (cubed - (2.0 * squared)) + amount;
  7025. var part4 = cubed - squared;
  7026. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7027. };
  7028. /**
  7029. * Returns a random float number between and min and max values
  7030. */
  7031. Scalar.RandomRange = function (min, max) {
  7032. if (min === max)
  7033. return min;
  7034. return ((Math.random() * (max - min)) + min);
  7035. };
  7036. /**
  7037. * This function returns percentage of a number in a given range.
  7038. *
  7039. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7040. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7041. */
  7042. Scalar.RangeToPercent = function (number, min, max) {
  7043. return ((number - min) / (max - min));
  7044. };
  7045. /**
  7046. * This function returns number that corresponds to the percentage in a given range.
  7047. *
  7048. * PercentToRange(0.34,0,100) will return 34.
  7049. */
  7050. Scalar.PercentToRange = function (percent, min, max) {
  7051. return ((max - min) * percent + min);
  7052. };
  7053. /**
  7054. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7055. * @param angle The angle to normalize in radian.
  7056. * @return The converted angle.
  7057. */
  7058. Scalar.NormalizeRadians = function (angle) {
  7059. // More precise but slower version kept for reference.
  7060. // angle = angle % Tools.TwoPi;
  7061. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7062. //if (angle > Math.PI) {
  7063. // angle -= Tools.TwoPi;
  7064. //}
  7065. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7066. return angle;
  7067. };
  7068. /**
  7069. * Two pi constants convenient for computation.
  7070. */
  7071. Scalar.TwoPi = Math.PI * 2;
  7072. return Scalar;
  7073. }());
  7074. BABYLON.Scalar = Scalar;
  7075. })(BABYLON || (BABYLON = {}));
  7076. //# sourceMappingURL=babylon.math.scalar.js.map
  7077. "use strict";
  7078. //# sourceMappingURL=babylon.mixins.js.map
  7079. "use strict";
  7080. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7081. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7082. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7083. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7084. //# sourceMappingURL=babylon.webgl2.js.map
  7085. "use strict";
  7086. var BABYLON;
  7087. (function (BABYLON) {
  7088. var __decoratorInitialStore = {};
  7089. var __mergedStore = {};
  7090. var _copySource = function (creationFunction, source, instanciate) {
  7091. var destination = creationFunction();
  7092. // Tags
  7093. if (BABYLON.Tags) {
  7094. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7095. }
  7096. var classStore = getMergedStore(destination);
  7097. // Properties
  7098. for (var property in classStore) {
  7099. var propertyDescriptor = classStore[property];
  7100. var sourceProperty = source[property];
  7101. var propertyType = propertyDescriptor.type;
  7102. if (sourceProperty !== undefined && sourceProperty !== null) {
  7103. switch (propertyType) {
  7104. case 0: // Value
  7105. case 6:// Mesh reference
  7106. destination[property] = sourceProperty;
  7107. break;
  7108. case 1:// Texture
  7109. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7110. break;
  7111. case 2: // Color3
  7112. case 3: // FresnelParameters
  7113. case 4: // Vector2
  7114. case 5: // Vector3
  7115. case 7: // Color Curves
  7116. case 10:// Quaternion
  7117. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7118. break;
  7119. }
  7120. }
  7121. }
  7122. return destination;
  7123. };
  7124. function getDirectStore(target) {
  7125. var classKey = target.getClassName();
  7126. if (!__decoratorInitialStore[classKey]) {
  7127. __decoratorInitialStore[classKey] = {};
  7128. }
  7129. return __decoratorInitialStore[classKey];
  7130. }
  7131. /**
  7132. * Return the list of properties flagged as serializable
  7133. * @param target: host object
  7134. */
  7135. function getMergedStore(target) {
  7136. var classKey = target.getClassName();
  7137. if (__mergedStore[classKey]) {
  7138. return __mergedStore[classKey];
  7139. }
  7140. __mergedStore[classKey] = {};
  7141. var store = __mergedStore[classKey];
  7142. var currentTarget = target;
  7143. var currentKey = classKey;
  7144. while (currentKey) {
  7145. var initialStore = __decoratorInitialStore[currentKey];
  7146. for (var property in initialStore) {
  7147. store[property] = initialStore[property];
  7148. }
  7149. var parent_1 = void 0;
  7150. var done = false;
  7151. do {
  7152. parent_1 = Object.getPrototypeOf(currentTarget);
  7153. if (!parent_1.getClassName) {
  7154. done = true;
  7155. break;
  7156. }
  7157. if (parent_1.getClassName() !== currentKey) {
  7158. break;
  7159. }
  7160. currentTarget = parent_1;
  7161. } while (parent_1);
  7162. if (done) {
  7163. break;
  7164. }
  7165. currentKey = parent_1.getClassName();
  7166. currentTarget = parent_1;
  7167. }
  7168. return store;
  7169. }
  7170. function generateSerializableMember(type, sourceName) {
  7171. return function (target, propertyKey) {
  7172. var classStore = getDirectStore(target);
  7173. if (!classStore[propertyKey]) {
  7174. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7175. }
  7176. };
  7177. }
  7178. function generateExpandMember(setCallback, targetKey) {
  7179. if (targetKey === void 0) { targetKey = null; }
  7180. return function (target, propertyKey) {
  7181. var key = targetKey || ("_" + propertyKey);
  7182. Object.defineProperty(target, propertyKey, {
  7183. get: function () {
  7184. return this[key];
  7185. },
  7186. set: function (value) {
  7187. if (this[key] === value) {
  7188. return;
  7189. }
  7190. this[key] = value;
  7191. target[setCallback].apply(this);
  7192. },
  7193. enumerable: true,
  7194. configurable: true
  7195. });
  7196. };
  7197. }
  7198. function expandToProperty(callback, targetKey) {
  7199. if (targetKey === void 0) { targetKey = null; }
  7200. return generateExpandMember(callback, targetKey);
  7201. }
  7202. BABYLON.expandToProperty = expandToProperty;
  7203. function serialize(sourceName) {
  7204. return generateSerializableMember(0, sourceName); // value member
  7205. }
  7206. BABYLON.serialize = serialize;
  7207. function serializeAsTexture(sourceName) {
  7208. return generateSerializableMember(1, sourceName); // texture member
  7209. }
  7210. BABYLON.serializeAsTexture = serializeAsTexture;
  7211. function serializeAsColor3(sourceName) {
  7212. return generateSerializableMember(2, sourceName); // color3 member
  7213. }
  7214. BABYLON.serializeAsColor3 = serializeAsColor3;
  7215. function serializeAsFresnelParameters(sourceName) {
  7216. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7217. }
  7218. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7219. function serializeAsVector2(sourceName) {
  7220. return generateSerializableMember(4, sourceName); // vector2 member
  7221. }
  7222. BABYLON.serializeAsVector2 = serializeAsVector2;
  7223. function serializeAsVector3(sourceName) {
  7224. return generateSerializableMember(5, sourceName); // vector3 member
  7225. }
  7226. BABYLON.serializeAsVector3 = serializeAsVector3;
  7227. function serializeAsMeshReference(sourceName) {
  7228. return generateSerializableMember(6, sourceName); // mesh reference member
  7229. }
  7230. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7231. function serializeAsColorCurves(sourceName) {
  7232. return generateSerializableMember(7, sourceName); // color curves
  7233. }
  7234. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7235. function serializeAsColor4(sourceName) {
  7236. return generateSerializableMember(8, sourceName); // color 4
  7237. }
  7238. BABYLON.serializeAsColor4 = serializeAsColor4;
  7239. function serializeAsImageProcessingConfiguration(sourceName) {
  7240. return generateSerializableMember(9, sourceName); // image processing
  7241. }
  7242. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7243. function serializeAsQuaternion(sourceName) {
  7244. return generateSerializableMember(10, sourceName); // quaternion member
  7245. }
  7246. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7247. var SerializationHelper = /** @class */ (function () {
  7248. function SerializationHelper() {
  7249. }
  7250. SerializationHelper.Serialize = function (entity, serializationObject) {
  7251. if (!serializationObject) {
  7252. serializationObject = {};
  7253. }
  7254. // Tags
  7255. if (BABYLON.Tags) {
  7256. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7257. }
  7258. var serializedProperties = getMergedStore(entity);
  7259. // Properties
  7260. for (var property in serializedProperties) {
  7261. var propertyDescriptor = serializedProperties[property];
  7262. var targetPropertyName = propertyDescriptor.sourceName || property;
  7263. var propertyType = propertyDescriptor.type;
  7264. var sourceProperty = entity[property];
  7265. if (sourceProperty !== undefined && sourceProperty !== null) {
  7266. switch (propertyType) {
  7267. case 0:// Value
  7268. serializationObject[targetPropertyName] = sourceProperty;
  7269. break;
  7270. case 1:// Texture
  7271. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7272. break;
  7273. case 2:// Color3
  7274. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7275. break;
  7276. case 3:// FresnelParameters
  7277. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7278. break;
  7279. case 4:// Vector2
  7280. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7281. break;
  7282. case 5:// Vector3
  7283. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7284. break;
  7285. case 6:// Mesh reference
  7286. serializationObject[targetPropertyName] = sourceProperty.id;
  7287. break;
  7288. case 7:// Color Curves
  7289. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7290. break;
  7291. case 8:// Color 4
  7292. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7293. break;
  7294. case 9:// Image Processing
  7295. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7296. break;
  7297. }
  7298. }
  7299. }
  7300. return serializationObject;
  7301. };
  7302. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7303. if (rootUrl === void 0) { rootUrl = null; }
  7304. var destination = creationFunction();
  7305. if (!rootUrl) {
  7306. rootUrl = "";
  7307. }
  7308. // Tags
  7309. if (BABYLON.Tags) {
  7310. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7311. }
  7312. var classStore = getMergedStore(destination);
  7313. // Properties
  7314. for (var property in classStore) {
  7315. var propertyDescriptor = classStore[property];
  7316. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7317. var propertyType = propertyDescriptor.type;
  7318. if (sourceProperty !== undefined && sourceProperty !== null) {
  7319. var dest = destination;
  7320. switch (propertyType) {
  7321. case 0:// Value
  7322. dest[property] = sourceProperty;
  7323. break;
  7324. case 1:// Texture
  7325. if (scene) {
  7326. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7327. }
  7328. break;
  7329. case 2:// Color3
  7330. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7331. break;
  7332. case 3:// FresnelParameters
  7333. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7334. break;
  7335. case 4:// Vector2
  7336. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7337. break;
  7338. case 5:// Vector3
  7339. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7340. break;
  7341. case 6:// Mesh reference
  7342. if (scene) {
  7343. dest[property] = scene.getLastMeshByID(sourceProperty);
  7344. }
  7345. break;
  7346. case 7:// Color Curves
  7347. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7348. break;
  7349. case 8:// Color 4
  7350. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7351. break;
  7352. case 9:// Image Processing
  7353. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7354. break;
  7355. }
  7356. }
  7357. }
  7358. return destination;
  7359. };
  7360. SerializationHelper.Clone = function (creationFunction, source) {
  7361. return _copySource(creationFunction, source, false);
  7362. };
  7363. SerializationHelper.Instanciate = function (creationFunction, source) {
  7364. return _copySource(creationFunction, source, true);
  7365. };
  7366. return SerializationHelper;
  7367. }());
  7368. BABYLON.SerializationHelper = SerializationHelper;
  7369. })(BABYLON || (BABYLON = {}));
  7370. //# sourceMappingURL=babylon.decorators.js.map
  7371. "use strict";
  7372. var BABYLON;
  7373. (function (BABYLON) {
  7374. /**
  7375. * Wrapper class for promise with external resolve and reject.
  7376. */
  7377. var Deferred = /** @class */ (function () {
  7378. /**
  7379. * Constructor for this deferred object.
  7380. */
  7381. function Deferred() {
  7382. var _this = this;
  7383. this.promise = new Promise(function (resolve, reject) {
  7384. _this._resolve = resolve;
  7385. _this._reject = reject;
  7386. });
  7387. }
  7388. Object.defineProperty(Deferred.prototype, "resolve", {
  7389. /**
  7390. * The resolve method of the promise associated with this deferred object.
  7391. */
  7392. get: function () {
  7393. return this._resolve;
  7394. },
  7395. enumerable: true,
  7396. configurable: true
  7397. });
  7398. Object.defineProperty(Deferred.prototype, "reject", {
  7399. /**
  7400. * The reject method of the promise associated with this deferred object.
  7401. */
  7402. get: function () {
  7403. return this._reject;
  7404. },
  7405. enumerable: true,
  7406. configurable: true
  7407. });
  7408. return Deferred;
  7409. }());
  7410. BABYLON.Deferred = Deferred;
  7411. })(BABYLON || (BABYLON = {}));
  7412. //# sourceMappingURL=babylon.deferred.js.map
  7413. "use strict";
  7414. var BABYLON;
  7415. (function (BABYLON) {
  7416. /**
  7417. * A class serves as a medium between the observable and its observers
  7418. */
  7419. var EventState = /** @class */ (function () {
  7420. /**
  7421. * Create a new EventState
  7422. * @param mask defines the mask associated with this state
  7423. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7424. * @param target defines the original target of the state
  7425. * @param currentTarget defines the current target of the state
  7426. */
  7427. function EventState(mask, skipNextObservers, target, currentTarget) {
  7428. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7429. this.initalize(mask, skipNextObservers, target, currentTarget);
  7430. }
  7431. /**
  7432. * Initialize the current event state
  7433. * @param mask defines the mask associated with this state
  7434. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7435. * @param target defines the original target of the state
  7436. * @param currentTarget defines the current target of the state
  7437. * @returns the current event state
  7438. */
  7439. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7440. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7441. this.mask = mask;
  7442. this.skipNextObservers = skipNextObservers;
  7443. this.target = target;
  7444. this.currentTarget = currentTarget;
  7445. return this;
  7446. };
  7447. return EventState;
  7448. }());
  7449. BABYLON.EventState = EventState;
  7450. /**
  7451. * Represent an Observer registered to a given Observable object.
  7452. */
  7453. var Observer = /** @class */ (function () {
  7454. /**
  7455. * Creates a new observer
  7456. * @param callback defines the callback to call when the observer is notified
  7457. * @param mask defines the mask of the observer (used to filter notifications)
  7458. * @param scope defines the current scope used to restore the JS context
  7459. */
  7460. function Observer(
  7461. /**
  7462. * Defines the callback to call when the observer is notified
  7463. */
  7464. callback,
  7465. /**
  7466. * Defines the mask of the observer (used to filter notifications)
  7467. */
  7468. mask,
  7469. /**
  7470. * Defines the current scope used to restore the JS context
  7471. */
  7472. scope) {
  7473. if (scope === void 0) { scope = null; }
  7474. this.callback = callback;
  7475. this.mask = mask;
  7476. this.scope = scope;
  7477. /** @ignore */
  7478. this._willBeUnregistered = false;
  7479. /**
  7480. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7481. */
  7482. this.unregisterOnNextCall = false;
  7483. }
  7484. return Observer;
  7485. }());
  7486. BABYLON.Observer = Observer;
  7487. /**
  7488. * Represent a list of observers registered to multiple Observables object.
  7489. */
  7490. var MultiObserver = /** @class */ (function () {
  7491. function MultiObserver() {
  7492. }
  7493. /**
  7494. * Release associated resources
  7495. */
  7496. MultiObserver.prototype.dispose = function () {
  7497. if (this._observers && this._observables) {
  7498. for (var index = 0; index < this._observers.length; index++) {
  7499. this._observables[index].remove(this._observers[index]);
  7500. }
  7501. }
  7502. this._observers = null;
  7503. this._observables = null;
  7504. };
  7505. /**
  7506. * Raise a callback when one of the observable will notify
  7507. * @param observables defines a list of observables to watch
  7508. * @param callback defines the callback to call on notification
  7509. * @param mask defines the mask used to filter notifications
  7510. * @param scope defines the current scope used to restore the JS context
  7511. * @returns the new MultiObserver
  7512. */
  7513. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7514. if (mask === void 0) { mask = -1; }
  7515. if (scope === void 0) { scope = null; }
  7516. var result = new MultiObserver();
  7517. result._observers = new Array();
  7518. result._observables = observables;
  7519. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7520. var observable = observables_1[_i];
  7521. var observer = observable.add(callback, mask, false, scope);
  7522. if (observer) {
  7523. result._observers.push(observer);
  7524. }
  7525. }
  7526. return result;
  7527. };
  7528. return MultiObserver;
  7529. }());
  7530. BABYLON.MultiObserver = MultiObserver;
  7531. /**
  7532. * The Observable class is a simple implementation of the Observable pattern.
  7533. * 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.
  7534. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7535. * 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).
  7536. * 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.
  7537. */
  7538. var Observable = /** @class */ (function () {
  7539. /**
  7540. * Creates a new observable
  7541. * @param onObserverAdded defines a callback to call when a new observer is added
  7542. */
  7543. function Observable(onObserverAdded) {
  7544. this._observers = new Array();
  7545. this._eventState = new EventState(0);
  7546. if (onObserverAdded) {
  7547. this._onObserverAdded = onObserverAdded;
  7548. }
  7549. }
  7550. /**
  7551. * Create a new Observer with the specified callback
  7552. * @param callback the callback that will be executed for that Observer
  7553. * @param mask the mask used to filter observers
  7554. * @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.
  7555. * @param scope optional scope for the callback to be called from
  7556. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7557. * @returns the new observer created for the callback
  7558. */
  7559. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7560. if (mask === void 0) { mask = -1; }
  7561. if (insertFirst === void 0) { insertFirst = false; }
  7562. if (scope === void 0) { scope = null; }
  7563. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7564. if (!callback) {
  7565. return null;
  7566. }
  7567. var observer = new Observer(callback, mask, scope);
  7568. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7569. if (insertFirst) {
  7570. this._observers.unshift(observer);
  7571. }
  7572. else {
  7573. this._observers.push(observer);
  7574. }
  7575. if (this._onObserverAdded) {
  7576. this._onObserverAdded(observer);
  7577. }
  7578. return observer;
  7579. };
  7580. /**
  7581. * Remove an Observer from the Observable object
  7582. * @param observer the instance of the Observer to remove
  7583. * @returns false if it doesn't belong to this Observable
  7584. */
  7585. Observable.prototype.remove = function (observer) {
  7586. if (!observer) {
  7587. return false;
  7588. }
  7589. var index = this._observers.indexOf(observer);
  7590. if (index !== -1) {
  7591. this._observers.splice(index, 1);
  7592. return true;
  7593. }
  7594. return false;
  7595. };
  7596. /**
  7597. * Remove a callback from the Observable object
  7598. * @param callback the callback to remove
  7599. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7600. * @returns false if it doesn't belong to this Observable
  7601. */
  7602. Observable.prototype.removeCallback = function (callback, scope) {
  7603. for (var index = 0; index < this._observers.length; index++) {
  7604. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7605. this._observers.splice(index, 1);
  7606. return true;
  7607. }
  7608. }
  7609. return false;
  7610. };
  7611. Observable.prototype._deferUnregister = function (observer) {
  7612. var _this = this;
  7613. observer.unregisterOnNextCall = false;
  7614. observer._willBeUnregistered = true;
  7615. BABYLON.Tools.SetImmediate(function () {
  7616. _this.remove(observer);
  7617. });
  7618. };
  7619. /**
  7620. * Notify all Observers by calling their respective callback with the given data
  7621. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7622. * @param eventData defines the data to send to all observers
  7623. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7624. * @param target defines the original target of the state
  7625. * @param currentTarget defines the current target of the state
  7626. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7627. */
  7628. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7629. if (mask === void 0) { mask = -1; }
  7630. if (!this._observers.length) {
  7631. return true;
  7632. }
  7633. var state = this._eventState;
  7634. state.mask = mask;
  7635. state.target = target;
  7636. state.currentTarget = currentTarget;
  7637. state.skipNextObservers = false;
  7638. state.lastReturnValue = eventData;
  7639. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7640. var obs = _a[_i];
  7641. if (obs._willBeUnregistered) {
  7642. continue;
  7643. }
  7644. if (obs.mask & mask) {
  7645. if (obs.scope) {
  7646. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7647. }
  7648. else {
  7649. state.lastReturnValue = obs.callback(eventData, state);
  7650. }
  7651. if (obs.unregisterOnNextCall) {
  7652. this._deferUnregister(obs);
  7653. }
  7654. }
  7655. if (state.skipNextObservers) {
  7656. return false;
  7657. }
  7658. }
  7659. return true;
  7660. };
  7661. /**
  7662. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7663. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7664. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7665. * and it is crucial that all callbacks will be executed.
  7666. * The order of the callbacks is kept, callbacks are not executed parallel.
  7667. *
  7668. * @param eventData The data to be sent to each callback
  7669. * @param mask is used to filter observers defaults to -1
  7670. * @param target defines the callback target (see EventState)
  7671. * @param currentTarget defines he current object in the bubbling phase
  7672. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7673. */
  7674. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7675. var _this = this;
  7676. if (mask === void 0) { mask = -1; }
  7677. // create an empty promise
  7678. var p = Promise.resolve(eventData);
  7679. // no observers? return this promise.
  7680. if (!this._observers.length) {
  7681. return p;
  7682. }
  7683. var state = this._eventState;
  7684. state.mask = mask;
  7685. state.target = target;
  7686. state.currentTarget = currentTarget;
  7687. state.skipNextObservers = false;
  7688. // execute one callback after another (not using Promise.all, the order is important)
  7689. this._observers.forEach(function (obs) {
  7690. if (state.skipNextObservers) {
  7691. return;
  7692. }
  7693. if (obs._willBeUnregistered) {
  7694. return;
  7695. }
  7696. if (obs.mask & mask) {
  7697. if (obs.scope) {
  7698. p = p.then(function (lastReturnedValue) {
  7699. state.lastReturnValue = lastReturnedValue;
  7700. return obs.callback.apply(obs.scope, [eventData, state]);
  7701. });
  7702. }
  7703. else {
  7704. p = p.then(function (lastReturnedValue) {
  7705. state.lastReturnValue = lastReturnedValue;
  7706. return obs.callback(eventData, state);
  7707. });
  7708. }
  7709. if (obs.unregisterOnNextCall) {
  7710. _this._deferUnregister(obs);
  7711. }
  7712. }
  7713. });
  7714. // return the eventData
  7715. return p.then(function () { return eventData; });
  7716. };
  7717. /**
  7718. * Notify a specific observer
  7719. * @param observer defines the observer to notify
  7720. * @param eventData defines the data to be sent to each callback
  7721. * @param mask is used to filter observers defaults to -1
  7722. */
  7723. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7724. if (mask === void 0) { mask = -1; }
  7725. var state = this._eventState;
  7726. state.mask = mask;
  7727. state.skipNextObservers = false;
  7728. observer.callback(eventData, state);
  7729. };
  7730. /**
  7731. * Gets a boolean indicating if the observable has at least one observer
  7732. * @returns true is the Observable has at least one Observer registered
  7733. */
  7734. Observable.prototype.hasObservers = function () {
  7735. return this._observers.length > 0;
  7736. };
  7737. /**
  7738. * Clear the list of observers
  7739. */
  7740. Observable.prototype.clear = function () {
  7741. this._observers = new Array();
  7742. this._onObserverAdded = null;
  7743. };
  7744. /**
  7745. * Clone the current observable
  7746. * @returns a new observable
  7747. */
  7748. Observable.prototype.clone = function () {
  7749. var result = new Observable();
  7750. result._observers = this._observers.slice(0);
  7751. return result;
  7752. };
  7753. /**
  7754. * Does this observable handles observer registered with a given mask
  7755. * @param mask defines the mask to be tested
  7756. * @return whether or not one observer registered with the given mask is handeled
  7757. **/
  7758. Observable.prototype.hasSpecificMask = function (mask) {
  7759. if (mask === void 0) { mask = -1; }
  7760. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7761. var obs = _a[_i];
  7762. if (obs.mask & mask || obs.mask === mask) {
  7763. return true;
  7764. }
  7765. }
  7766. return false;
  7767. };
  7768. return Observable;
  7769. }());
  7770. BABYLON.Observable = Observable;
  7771. })(BABYLON || (BABYLON = {}));
  7772. //# sourceMappingURL=babylon.observable.js.map
  7773. "use strict";
  7774. var BABYLON;
  7775. (function (BABYLON) {
  7776. var SmartArray = /** @class */ (function () {
  7777. function SmartArray(capacity) {
  7778. this.length = 0;
  7779. this.data = new Array(capacity);
  7780. this._id = SmartArray._GlobalId++;
  7781. }
  7782. SmartArray.prototype.push = function (value) {
  7783. this.data[this.length++] = value;
  7784. if (this.length > this.data.length) {
  7785. this.data.length *= 2;
  7786. }
  7787. };
  7788. SmartArray.prototype.forEach = function (func) {
  7789. for (var index = 0; index < this.length; index++) {
  7790. func(this.data[index]);
  7791. }
  7792. };
  7793. SmartArray.prototype.sort = function (compareFn) {
  7794. this.data.sort(compareFn);
  7795. };
  7796. SmartArray.prototype.reset = function () {
  7797. this.length = 0;
  7798. };
  7799. SmartArray.prototype.dispose = function () {
  7800. this.reset();
  7801. if (this.data) {
  7802. this.data.length = 0;
  7803. this.data = [];
  7804. }
  7805. };
  7806. SmartArray.prototype.concat = function (array) {
  7807. if (array.length === 0) {
  7808. return;
  7809. }
  7810. if (this.length + array.length > this.data.length) {
  7811. this.data.length = (this.length + array.length) * 2;
  7812. }
  7813. for (var index = 0; index < array.length; index++) {
  7814. this.data[this.length++] = (array.data || array)[index];
  7815. }
  7816. };
  7817. SmartArray.prototype.indexOf = function (value) {
  7818. var position = this.data.indexOf(value);
  7819. if (position >= this.length) {
  7820. return -1;
  7821. }
  7822. return position;
  7823. };
  7824. SmartArray.prototype.contains = function (value) {
  7825. return this.data.indexOf(value) !== -1;
  7826. };
  7827. // Statics
  7828. SmartArray._GlobalId = 0;
  7829. return SmartArray;
  7830. }());
  7831. BABYLON.SmartArray = SmartArray;
  7832. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7833. __extends(SmartArrayNoDuplicate, _super);
  7834. function SmartArrayNoDuplicate() {
  7835. var _this = _super !== null && _super.apply(this, arguments) || this;
  7836. _this._duplicateId = 0;
  7837. return _this;
  7838. }
  7839. SmartArrayNoDuplicate.prototype.push = function (value) {
  7840. _super.prototype.push.call(this, value);
  7841. if (!value.__smartArrayFlags) {
  7842. value.__smartArrayFlags = {};
  7843. }
  7844. value.__smartArrayFlags[this._id] = this._duplicateId;
  7845. };
  7846. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7847. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7848. return false;
  7849. }
  7850. this.push(value);
  7851. return true;
  7852. };
  7853. SmartArrayNoDuplicate.prototype.reset = function () {
  7854. _super.prototype.reset.call(this);
  7855. this._duplicateId++;
  7856. };
  7857. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7858. if (array.length === 0) {
  7859. return;
  7860. }
  7861. if (this.length + array.length > this.data.length) {
  7862. this.data.length = (this.length + array.length) * 2;
  7863. }
  7864. for (var index = 0; index < array.length; index++) {
  7865. var item = (array.data || array)[index];
  7866. this.pushNoDuplicate(item);
  7867. }
  7868. };
  7869. return SmartArrayNoDuplicate;
  7870. }(SmartArray));
  7871. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7872. })(BABYLON || (BABYLON = {}));
  7873. //# sourceMappingURL=babylon.smartArray.js.map
  7874. "use strict";
  7875. var BABYLON;
  7876. (function (BABYLON) {
  7877. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7878. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7879. var LoadFileError = /** @class */ (function (_super) {
  7880. __extends(LoadFileError, _super);
  7881. function LoadFileError(message, request) {
  7882. var _this = _super.call(this, message) || this;
  7883. _this.request = request;
  7884. _this.name = "LoadFileError";
  7885. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7886. return _this;
  7887. }
  7888. // Polyfill for Object.setPrototypeOf if necessary.
  7889. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7890. return LoadFileError;
  7891. }(Error));
  7892. BABYLON.LoadFileError = LoadFileError;
  7893. var RetryStrategy = /** @class */ (function () {
  7894. function RetryStrategy() {
  7895. }
  7896. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7897. if (maxRetries === void 0) { maxRetries = 3; }
  7898. if (baseInterval === void 0) { baseInterval = 500; }
  7899. return function (url, request, retryIndex) {
  7900. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7901. return -1;
  7902. }
  7903. return Math.pow(2, retryIndex) * baseInterval;
  7904. };
  7905. };
  7906. return RetryStrategy;
  7907. }());
  7908. BABYLON.RetryStrategy = RetryStrategy;
  7909. // Screenshots
  7910. var screenshotCanvas;
  7911. var cloneValue = function (source, destinationObject) {
  7912. if (!source)
  7913. return null;
  7914. if (source instanceof BABYLON.Mesh) {
  7915. return null;
  7916. }
  7917. if (source instanceof BABYLON.SubMesh) {
  7918. return source.clone(destinationObject);
  7919. }
  7920. else if (source.clone) {
  7921. return source.clone();
  7922. }
  7923. return null;
  7924. };
  7925. var Tools = /** @class */ (function () {
  7926. function Tools() {
  7927. }
  7928. /**
  7929. * Interpolates between a and b via alpha
  7930. * @param a The lower value (returned when alpha = 0)
  7931. * @param b The upper value (returned when alpha = 1)
  7932. * @param alpha The interpolation-factor
  7933. * @return The mixed value
  7934. */
  7935. Tools.Mix = function (a, b, alpha) {
  7936. return a * (1 - alpha) + b * alpha;
  7937. };
  7938. Tools.Instantiate = function (className) {
  7939. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7940. return Tools.RegisteredExternalClasses[className];
  7941. }
  7942. var arr = className.split(".");
  7943. var fn = (window || this);
  7944. for (var i = 0, len = arr.length; i < len; i++) {
  7945. fn = fn[arr[i]];
  7946. }
  7947. if (typeof fn !== "function") {
  7948. return null;
  7949. }
  7950. return fn;
  7951. };
  7952. /**
  7953. * Provides a slice function that will work even on IE
  7954. * @param data defines the array to slice
  7955. * @returns the new sliced array
  7956. */
  7957. Tools.Slice = function (data) {
  7958. if (data.slice) {
  7959. return data.slice();
  7960. }
  7961. return Array.prototype.slice.call(data);
  7962. };
  7963. Tools.SetImmediate = function (action) {
  7964. if (window.setImmediate) {
  7965. window.setImmediate(action);
  7966. }
  7967. else {
  7968. setTimeout(action, 1);
  7969. }
  7970. };
  7971. Tools.IsExponentOfTwo = function (value) {
  7972. var count = 1;
  7973. do {
  7974. count *= 2;
  7975. } while (count < value);
  7976. return count === value;
  7977. };
  7978. /**
  7979. * Find the next highest power of two.
  7980. * @param x Number to start search from.
  7981. * @return Next highest power of two.
  7982. */
  7983. Tools.CeilingPOT = function (x) {
  7984. x--;
  7985. x |= x >> 1;
  7986. x |= x >> 2;
  7987. x |= x >> 4;
  7988. x |= x >> 8;
  7989. x |= x >> 16;
  7990. x++;
  7991. return x;
  7992. };
  7993. /**
  7994. * Find the next lowest power of two.
  7995. * @param x Number to start search from.
  7996. * @return Next lowest power of two.
  7997. */
  7998. Tools.FloorPOT = function (x) {
  7999. x = x | (x >> 1);
  8000. x = x | (x >> 2);
  8001. x = x | (x >> 4);
  8002. x = x | (x >> 8);
  8003. x = x | (x >> 16);
  8004. return x - (x >> 1);
  8005. };
  8006. /**
  8007. * Find the nearest power of two.
  8008. * @param x Number to start search from.
  8009. * @return Next nearest power of two.
  8010. */
  8011. Tools.NearestPOT = function (x) {
  8012. var c = Tools.CeilingPOT(x);
  8013. var f = Tools.FloorPOT(x);
  8014. return (c - x) > (x - f) ? f : c;
  8015. };
  8016. Tools.GetExponentOfTwo = function (value, max, mode) {
  8017. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8018. var pot;
  8019. switch (mode) {
  8020. case BABYLON.Engine.SCALEMODE_FLOOR:
  8021. pot = Tools.FloorPOT(value);
  8022. break;
  8023. case BABYLON.Engine.SCALEMODE_NEAREST:
  8024. pot = Tools.NearestPOT(value);
  8025. break;
  8026. case BABYLON.Engine.SCALEMODE_CEILING:
  8027. default:
  8028. pot = Tools.CeilingPOT(value);
  8029. break;
  8030. }
  8031. return Math.min(pot, max);
  8032. };
  8033. Tools.GetFilename = function (path) {
  8034. var index = path.lastIndexOf("/");
  8035. if (index < 0)
  8036. return path;
  8037. return path.substring(index + 1);
  8038. };
  8039. /**
  8040. * Extracts the "folder" part of a path (everything before the filename).
  8041. * @param uri The URI to extract the info from
  8042. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8043. * @returns The "folder" part of the path
  8044. */
  8045. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8046. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8047. var index = uri.lastIndexOf("/");
  8048. if (index < 0) {
  8049. if (returnUnchangedIfNoSlash) {
  8050. return uri;
  8051. }
  8052. return "";
  8053. }
  8054. return uri.substring(0, index + 1);
  8055. };
  8056. Tools.GetDOMTextContent = function (element) {
  8057. var result = "";
  8058. var child = element.firstChild;
  8059. while (child) {
  8060. if (child.nodeType === 3) {
  8061. result += child.textContent;
  8062. }
  8063. child = child.nextSibling;
  8064. }
  8065. return result;
  8066. };
  8067. Tools.ToDegrees = function (angle) {
  8068. return angle * 180 / Math.PI;
  8069. };
  8070. Tools.ToRadians = function (angle) {
  8071. return angle * Math.PI / 180;
  8072. };
  8073. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8074. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8075. var output = "";
  8076. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8077. var i = 0;
  8078. var bytes = new Uint8Array(buffer);
  8079. while (i < bytes.length) {
  8080. chr1 = bytes[i++];
  8081. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8082. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8083. enc1 = chr1 >> 2;
  8084. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8085. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8086. enc4 = chr3 & 63;
  8087. if (isNaN(chr2)) {
  8088. enc3 = enc4 = 64;
  8089. }
  8090. else if (isNaN(chr3)) {
  8091. enc4 = 64;
  8092. }
  8093. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8094. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8095. }
  8096. return "data:image/png;base64," + output;
  8097. };
  8098. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8099. if (bias === void 0) { bias = null; }
  8100. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8101. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8102. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8103. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8104. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8105. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8106. }
  8107. if (bias) {
  8108. minimum.x -= minimum.x * bias.x + bias.y;
  8109. minimum.y -= minimum.y * bias.x + bias.y;
  8110. minimum.z -= minimum.z * bias.x + bias.y;
  8111. maximum.x += maximum.x * bias.x + bias.y;
  8112. maximum.y += maximum.y * bias.x + bias.y;
  8113. maximum.z += maximum.z * bias.x + bias.y;
  8114. }
  8115. return {
  8116. minimum: minimum,
  8117. maximum: maximum
  8118. };
  8119. };
  8120. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8121. if (bias === void 0) { bias = null; }
  8122. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8123. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8124. if (!stride) {
  8125. stride = 3;
  8126. }
  8127. for (var index = start; index < start + count; index++) {
  8128. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8129. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8130. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8131. }
  8132. if (bias) {
  8133. minimum.x -= minimum.x * bias.x + bias.y;
  8134. minimum.y -= minimum.y * bias.x + bias.y;
  8135. minimum.z -= minimum.z * bias.x + bias.y;
  8136. maximum.x += maximum.x * bias.x + bias.y;
  8137. maximum.y += maximum.y * bias.x + bias.y;
  8138. maximum.z += maximum.z * bias.x + bias.y;
  8139. }
  8140. return {
  8141. minimum: minimum,
  8142. maximum: maximum
  8143. };
  8144. };
  8145. Tools.Vector2ArrayFeeder = function (array) {
  8146. return function (index) {
  8147. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8148. var length = isFloatArray ? array.length / 2 : array.length;
  8149. if (index >= length) {
  8150. return null;
  8151. }
  8152. if (isFloatArray) {
  8153. var fa = array;
  8154. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8155. }
  8156. var a = array;
  8157. return a[index];
  8158. };
  8159. };
  8160. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8161. if (bias === void 0) { bias = null; }
  8162. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8163. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8164. var i = 0;
  8165. var cur = feeder(i++);
  8166. while (cur) {
  8167. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8168. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8169. cur = feeder(i++);
  8170. }
  8171. if (bias) {
  8172. minimum.x -= minimum.x * bias.x + bias.y;
  8173. minimum.y -= minimum.y * bias.x + bias.y;
  8174. maximum.x += maximum.x * bias.x + bias.y;
  8175. maximum.y += maximum.y * bias.x + bias.y;
  8176. }
  8177. return {
  8178. minimum: minimum,
  8179. maximum: maximum
  8180. };
  8181. };
  8182. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8183. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8184. return null;
  8185. return Array.isArray(obj) ? obj : [obj];
  8186. };
  8187. // Misc.
  8188. Tools.GetPointerPrefix = function () {
  8189. var eventPrefix = "pointer";
  8190. // Check if pointer events are supported
  8191. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8192. eventPrefix = "mouse";
  8193. }
  8194. return eventPrefix;
  8195. };
  8196. /**
  8197. * @param func - the function to be called
  8198. * @param requester - the object that will request the next frame. Falls back to window.
  8199. */
  8200. Tools.QueueNewFrame = function (func, requester) {
  8201. if (!Tools.IsWindowObjectExist()) {
  8202. return setTimeout(func, 16);
  8203. }
  8204. if (!requester) {
  8205. requester = window;
  8206. }
  8207. if (requester.requestAnimationFrame) {
  8208. return requester.requestAnimationFrame(func);
  8209. }
  8210. else if (requester.msRequestAnimationFrame) {
  8211. return requester.msRequestAnimationFrame(func);
  8212. }
  8213. else if (requester.webkitRequestAnimationFrame) {
  8214. return requester.webkitRequestAnimationFrame(func);
  8215. }
  8216. else if (requester.mozRequestAnimationFrame) {
  8217. return requester.mozRequestAnimationFrame(func);
  8218. }
  8219. else if (requester.oRequestAnimationFrame) {
  8220. return requester.oRequestAnimationFrame(func);
  8221. }
  8222. else {
  8223. return window.setTimeout(func, 16);
  8224. }
  8225. };
  8226. Tools.RequestFullscreen = function (element) {
  8227. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8228. if (!requestFunction)
  8229. return;
  8230. requestFunction.call(element);
  8231. };
  8232. Tools.ExitFullscreen = function () {
  8233. if (document.exitFullscreen) {
  8234. document.exitFullscreen();
  8235. }
  8236. else if (document.mozCancelFullScreen) {
  8237. document.mozCancelFullScreen();
  8238. }
  8239. else if (document.webkitCancelFullScreen) {
  8240. document.webkitCancelFullScreen();
  8241. }
  8242. else if (document.msCancelFullScreen) {
  8243. document.msCancelFullScreen();
  8244. }
  8245. };
  8246. Tools.SetCorsBehavior = function (url, element) {
  8247. if (url && url.indexOf("data:") === 0) {
  8248. return;
  8249. }
  8250. if (Tools.CorsBehavior) {
  8251. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8252. element.crossOrigin = Tools.CorsBehavior;
  8253. }
  8254. else {
  8255. var result = Tools.CorsBehavior(url);
  8256. if (result) {
  8257. element.crossOrigin = result;
  8258. }
  8259. }
  8260. }
  8261. };
  8262. // External files
  8263. Tools.CleanUrl = function (url) {
  8264. url = url.replace(/#/mg, "%23");
  8265. return url;
  8266. };
  8267. Tools.LoadImage = function (url, onLoad, onError, database) {
  8268. if (url instanceof ArrayBuffer) {
  8269. url = Tools.EncodeArrayBufferTobase64(url);
  8270. }
  8271. url = Tools.CleanUrl(url);
  8272. url = Tools.PreprocessUrl(url);
  8273. var img = new Image();
  8274. Tools.SetCorsBehavior(url, img);
  8275. var loadHandler = function () {
  8276. img.removeEventListener("load", loadHandler);
  8277. img.removeEventListener("error", errorHandler);
  8278. onLoad(img);
  8279. };
  8280. var errorHandler = function (err) {
  8281. img.removeEventListener("load", loadHandler);
  8282. img.removeEventListener("error", errorHandler);
  8283. Tools.Error("Error while trying to load image: " + url);
  8284. if (onError) {
  8285. onError("Error while trying to load image: " + url, err);
  8286. }
  8287. };
  8288. img.addEventListener("load", loadHandler);
  8289. img.addEventListener("error", errorHandler);
  8290. var noIndexedDB = function () {
  8291. img.src = url;
  8292. };
  8293. var loadFromIndexedDB = function () {
  8294. if (database) {
  8295. database.loadImageFromDB(url, img);
  8296. }
  8297. };
  8298. //ANY database to do!
  8299. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8300. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8301. }
  8302. else {
  8303. if (url.indexOf("file:") !== -1) {
  8304. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8305. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8306. try {
  8307. var blobURL;
  8308. try {
  8309. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8310. }
  8311. catch (ex) {
  8312. // Chrome doesn't support oneTimeOnly parameter
  8313. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8314. }
  8315. img.src = blobURL;
  8316. }
  8317. catch (e) {
  8318. img.src = "";
  8319. }
  8320. return img;
  8321. }
  8322. }
  8323. noIndexedDB();
  8324. }
  8325. return img;
  8326. };
  8327. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8328. url = Tools.CleanUrl(url);
  8329. url = Tools.PreprocessUrl(url);
  8330. // If file and file input are set
  8331. if (url.indexOf("file:") !== -1) {
  8332. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8333. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8334. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8335. }
  8336. }
  8337. var loadUrl = Tools.BaseUrl + url;
  8338. var aborted = false;
  8339. var fileRequest = {
  8340. onCompleteObservable: new BABYLON.Observable(),
  8341. abort: function () { return aborted = true; },
  8342. };
  8343. var requestFile = function () {
  8344. var request = new XMLHttpRequest();
  8345. var retryHandle = null;
  8346. fileRequest.abort = function () {
  8347. aborted = true;
  8348. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8349. request.abort();
  8350. }
  8351. if (retryHandle !== null) {
  8352. clearTimeout(retryHandle);
  8353. retryHandle = null;
  8354. }
  8355. };
  8356. var retryLoop = function (retryIndex) {
  8357. request.open('GET', loadUrl, true);
  8358. if (useArrayBuffer) {
  8359. request.responseType = "arraybuffer";
  8360. }
  8361. if (onProgress) {
  8362. request.addEventListener("progress", onProgress);
  8363. }
  8364. var onLoadEnd = function () {
  8365. request.removeEventListener("loadend", onLoadEnd);
  8366. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8367. fileRequest.onCompleteObservable.clear();
  8368. };
  8369. request.addEventListener("loadend", onLoadEnd);
  8370. var onReadyStateChange = function () {
  8371. if (aborted) {
  8372. return;
  8373. }
  8374. // In case of undefined state in some browsers.
  8375. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8376. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8377. request.removeEventListener("readystatechange", onReadyStateChange);
  8378. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8379. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8380. return;
  8381. }
  8382. var retryStrategy = Tools.DefaultRetryStrategy;
  8383. if (retryStrategy) {
  8384. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8385. if (waitTime !== -1) {
  8386. // Prevent the request from completing for retry.
  8387. request.removeEventListener("loadend", onLoadEnd);
  8388. request = new XMLHttpRequest();
  8389. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8390. return;
  8391. }
  8392. }
  8393. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8394. if (onError) {
  8395. onError(request, e);
  8396. }
  8397. else {
  8398. throw e;
  8399. }
  8400. }
  8401. };
  8402. request.addEventListener("readystatechange", onReadyStateChange);
  8403. request.send();
  8404. };
  8405. retryLoop(0);
  8406. };
  8407. // Caching all files
  8408. if (database && database.enableSceneOffline) {
  8409. var noIndexedDB_1 = function () {
  8410. if (!aborted) {
  8411. requestFile();
  8412. }
  8413. };
  8414. var loadFromIndexedDB = function () {
  8415. // TODO: database needs to support aborting and should return a IFileRequest
  8416. if (aborted) {
  8417. return;
  8418. }
  8419. if (database) {
  8420. database.loadFileFromDB(url, function (data) {
  8421. if (!aborted) {
  8422. onSuccess(data);
  8423. }
  8424. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8425. }, onProgress ? function (event) {
  8426. if (!aborted) {
  8427. onProgress(event);
  8428. }
  8429. } : undefined, noIndexedDB_1, useArrayBuffer);
  8430. }
  8431. };
  8432. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8433. }
  8434. else {
  8435. requestFile();
  8436. }
  8437. return fileRequest;
  8438. };
  8439. /**
  8440. * Load a script (identified by an url). When the url returns, the
  8441. * content of this file is added into a new script element, attached to the DOM (body element)
  8442. */
  8443. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8444. var head = document.getElementsByTagName('head')[0];
  8445. var script = document.createElement('script');
  8446. script.type = 'text/javascript';
  8447. script.src = scriptUrl;
  8448. script.onload = function () {
  8449. if (onSuccess) {
  8450. onSuccess();
  8451. }
  8452. };
  8453. script.onerror = function (e) {
  8454. if (onError) {
  8455. onError("Unable to load script", e);
  8456. }
  8457. };
  8458. head.appendChild(script);
  8459. };
  8460. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8461. var reader = new FileReader();
  8462. var request = {
  8463. onCompleteObservable: new BABYLON.Observable(),
  8464. abort: function () { return reader.abort(); },
  8465. };
  8466. reader.onloadend = function (e) {
  8467. request.onCompleteObservable.notifyObservers(request);
  8468. };
  8469. reader.onload = function (e) {
  8470. //target doesn't have result from ts 1.3
  8471. callback(e.target['result']);
  8472. };
  8473. reader.onprogress = progressCallback;
  8474. reader.readAsDataURL(fileToLoad);
  8475. return request;
  8476. };
  8477. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8478. var reader = new FileReader();
  8479. var request = {
  8480. onCompleteObservable: new BABYLON.Observable(),
  8481. abort: function () { return reader.abort(); },
  8482. };
  8483. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8484. reader.onerror = function (e) {
  8485. Tools.Log("Error while reading file: " + fileToLoad.name);
  8486. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8487. };
  8488. reader.onload = function (e) {
  8489. //target doesn't have result from ts 1.3
  8490. callback(e.target['result']);
  8491. };
  8492. if (progressCallBack) {
  8493. reader.onprogress = progressCallBack;
  8494. }
  8495. if (!useArrayBuffer) {
  8496. // Asynchronous read
  8497. reader.readAsText(fileToLoad);
  8498. }
  8499. else {
  8500. reader.readAsArrayBuffer(fileToLoad);
  8501. }
  8502. return request;
  8503. };
  8504. //returns a downloadable url to a file content.
  8505. Tools.FileAsURL = function (content) {
  8506. var fileBlob = new Blob([content]);
  8507. var url = window.URL || window.webkitURL;
  8508. var link = url.createObjectURL(fileBlob);
  8509. return link;
  8510. };
  8511. // Misc.
  8512. Tools.Format = function (value, decimals) {
  8513. if (decimals === void 0) { decimals = 2; }
  8514. return value.toFixed(decimals);
  8515. };
  8516. Tools.CheckExtends = function (v, min, max) {
  8517. if (v.x < min.x)
  8518. min.x = v.x;
  8519. if (v.y < min.y)
  8520. min.y = v.y;
  8521. if (v.z < min.z)
  8522. min.z = v.z;
  8523. if (v.x > max.x)
  8524. max.x = v.x;
  8525. if (v.y > max.y)
  8526. max.y = v.y;
  8527. if (v.z > max.z)
  8528. max.z = v.z;
  8529. };
  8530. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8531. for (var prop in source) {
  8532. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8533. continue;
  8534. }
  8535. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8536. continue;
  8537. }
  8538. var sourceValue = source[prop];
  8539. var typeOfSourceValue = typeof sourceValue;
  8540. if (typeOfSourceValue === "function") {
  8541. continue;
  8542. }
  8543. try {
  8544. if (typeOfSourceValue === "object") {
  8545. if (sourceValue instanceof Array) {
  8546. destination[prop] = [];
  8547. if (sourceValue.length > 0) {
  8548. if (typeof sourceValue[0] == "object") {
  8549. for (var index = 0; index < sourceValue.length; index++) {
  8550. var clonedValue = cloneValue(sourceValue[index], destination);
  8551. if (destination[prop].indexOf(clonedValue) === -1) {
  8552. destination[prop].push(clonedValue);
  8553. }
  8554. }
  8555. }
  8556. else {
  8557. destination[prop] = sourceValue.slice(0);
  8558. }
  8559. }
  8560. }
  8561. else {
  8562. destination[prop] = cloneValue(sourceValue, destination);
  8563. }
  8564. }
  8565. else {
  8566. destination[prop] = sourceValue;
  8567. }
  8568. }
  8569. catch (e) {
  8570. // Just ignore error (it could be because of a read-only property)
  8571. }
  8572. }
  8573. };
  8574. Tools.IsEmpty = function (obj) {
  8575. for (var i in obj) {
  8576. if (obj.hasOwnProperty(i)) {
  8577. return false;
  8578. }
  8579. }
  8580. return true;
  8581. };
  8582. Tools.RegisterTopRootEvents = function (events) {
  8583. for (var index = 0; index < events.length; index++) {
  8584. var event = events[index];
  8585. window.addEventListener(event.name, event.handler, false);
  8586. try {
  8587. if (window.parent) {
  8588. window.parent.addEventListener(event.name, event.handler, false);
  8589. }
  8590. }
  8591. catch (e) {
  8592. // Silently fails...
  8593. }
  8594. }
  8595. };
  8596. Tools.UnregisterTopRootEvents = function (events) {
  8597. for (var index = 0; index < events.length; index++) {
  8598. var event = events[index];
  8599. window.removeEventListener(event.name, event.handler);
  8600. try {
  8601. if (window.parent) {
  8602. window.parent.removeEventListener(event.name, event.handler);
  8603. }
  8604. }
  8605. catch (e) {
  8606. // Silently fails...
  8607. }
  8608. }
  8609. };
  8610. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8611. if (mimeType === void 0) { mimeType = "image/png"; }
  8612. // Read the contents of the framebuffer
  8613. var numberOfChannelsByLine = width * 4;
  8614. var halfHeight = height / 2;
  8615. //Reading datas from WebGL
  8616. var data = engine.readPixels(0, 0, width, height);
  8617. //To flip image on Y axis.
  8618. for (var i = 0; i < halfHeight; i++) {
  8619. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8620. var currentCell = j + i * numberOfChannelsByLine;
  8621. var targetLine = height - i - 1;
  8622. var targetCell = j + targetLine * numberOfChannelsByLine;
  8623. var temp = data[currentCell];
  8624. data[currentCell] = data[targetCell];
  8625. data[targetCell] = temp;
  8626. }
  8627. }
  8628. // Create a 2D canvas to store the result
  8629. if (!screenshotCanvas) {
  8630. screenshotCanvas = document.createElement('canvas');
  8631. }
  8632. screenshotCanvas.width = width;
  8633. screenshotCanvas.height = height;
  8634. var context = screenshotCanvas.getContext('2d');
  8635. if (context) {
  8636. // Copy the pixels to a 2D canvas
  8637. var imageData = context.createImageData(width, height);
  8638. var castData = (imageData.data);
  8639. castData.set(data);
  8640. context.putImageData(imageData, 0, 0);
  8641. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8642. }
  8643. };
  8644. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8645. if (mimeType === void 0) { mimeType = "image/png"; }
  8646. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8647. if (successCallback) {
  8648. successCallback(base64Image);
  8649. }
  8650. else {
  8651. // We need HTMLCanvasElement.toBlob for HD screenshots
  8652. if (!screenshotCanvas.toBlob) {
  8653. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8654. screenshotCanvas.toBlob = function (callback, type, quality) {
  8655. var _this = this;
  8656. setTimeout(function () {
  8657. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8658. for (var i = 0; i < len; i++) {
  8659. arr[i] = binStr.charCodeAt(i);
  8660. }
  8661. callback(new Blob([arr], { type: type || 'image/png' }));
  8662. });
  8663. };
  8664. }
  8665. screenshotCanvas.toBlob(function (blob) {
  8666. var url = URL.createObjectURL(blob);
  8667. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8668. if (("download" in document.createElement("a"))) {
  8669. var a = window.document.createElement("a");
  8670. a.href = url;
  8671. if (fileName) {
  8672. a.setAttribute("download", fileName);
  8673. }
  8674. else {
  8675. var date = new Date();
  8676. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8677. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8678. }
  8679. window.document.body.appendChild(a);
  8680. a.addEventListener("click", function () {
  8681. if (a.parentElement) {
  8682. a.parentElement.removeChild(a);
  8683. }
  8684. });
  8685. a.click();
  8686. }
  8687. else {
  8688. var newWindow = window.open("");
  8689. if (!newWindow)
  8690. return;
  8691. var img = newWindow.document.createElement("img");
  8692. img.onload = function () {
  8693. // no longer need to read the blob so it's revoked
  8694. URL.revokeObjectURL(url);
  8695. };
  8696. img.src = url;
  8697. newWindow.document.body.appendChild(img);
  8698. }
  8699. });
  8700. }
  8701. };
  8702. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8703. if (mimeType === void 0) { mimeType = "image/png"; }
  8704. var width;
  8705. var height;
  8706. // If a precision value is specified
  8707. if (size.precision) {
  8708. width = Math.round(engine.getRenderWidth() * size.precision);
  8709. height = Math.round(width / engine.getAspectRatio(camera));
  8710. }
  8711. else if (size.width && size.height) {
  8712. width = size.width;
  8713. height = size.height;
  8714. }
  8715. else if (size.width && !size.height) {
  8716. width = size.width;
  8717. height = Math.round(width / engine.getAspectRatio(camera));
  8718. }
  8719. else if (size.height && !size.width) {
  8720. height = size.height;
  8721. width = Math.round(height * engine.getAspectRatio(camera));
  8722. }
  8723. else if (!isNaN(size)) {
  8724. height = size;
  8725. width = size;
  8726. }
  8727. else {
  8728. Tools.Error("Invalid 'size' parameter !");
  8729. return;
  8730. }
  8731. if (!screenshotCanvas) {
  8732. screenshotCanvas = document.createElement('canvas');
  8733. }
  8734. screenshotCanvas.width = width;
  8735. screenshotCanvas.height = height;
  8736. var renderContext = screenshotCanvas.getContext("2d");
  8737. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8738. var newWidth = width;
  8739. var newHeight = newWidth / ratio;
  8740. if (newHeight > height) {
  8741. newHeight = height;
  8742. newWidth = newHeight * ratio;
  8743. }
  8744. var offsetX = Math.max(0, width - newWidth) / 2;
  8745. var offsetY = Math.max(0, height - newHeight) / 2;
  8746. var renderingCanvas = engine.getRenderingCanvas();
  8747. if (renderContext && renderingCanvas) {
  8748. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8749. }
  8750. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8751. };
  8752. /**
  8753. * Generates an image screenshot from the specified camera.
  8754. *
  8755. * @param engine The engine to use for rendering
  8756. * @param camera The camera to use for rendering
  8757. * @param size This parameter can be set to a single number or to an object with the
  8758. * following (optional) properties: precision, width, height. If a single number is passed,
  8759. * it will be used for both width and height. If an object is passed, the screenshot size
  8760. * will be derived from the parameters. The precision property is a multiplier allowing
  8761. * rendering at a higher or lower resolution.
  8762. * @param successCallback The callback receives a single parameter which contains the
  8763. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8764. * src parameter of an <img> to display it.
  8765. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8766. * Check your browser for supported MIME types.
  8767. * @param samples Texture samples (default: 1)
  8768. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8769. * @param fileName A name for for the downloaded file.
  8770. * @constructor
  8771. */
  8772. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8773. if (mimeType === void 0) { mimeType = "image/png"; }
  8774. if (samples === void 0) { samples = 1; }
  8775. if (antialiasing === void 0) { antialiasing = false; }
  8776. var width;
  8777. var height;
  8778. //If a precision value is specified
  8779. if (size.precision) {
  8780. width = Math.round(engine.getRenderWidth() * size.precision);
  8781. height = Math.round(width / engine.getAspectRatio(camera));
  8782. size = { width: width, height: height };
  8783. }
  8784. else if (size.width && size.height) {
  8785. width = size.width;
  8786. height = size.height;
  8787. }
  8788. else if (size.width && !size.height) {
  8789. width = size.width;
  8790. height = Math.round(width / engine.getAspectRatio(camera));
  8791. size = { width: width, height: height };
  8792. }
  8793. else if (size.height && !size.width) {
  8794. height = size.height;
  8795. width = Math.round(height * engine.getAspectRatio(camera));
  8796. size = { width: width, height: height };
  8797. }
  8798. else if (!isNaN(size)) {
  8799. height = size;
  8800. width = size;
  8801. }
  8802. else {
  8803. Tools.Error("Invalid 'size' parameter !");
  8804. return;
  8805. }
  8806. var scene = camera.getScene();
  8807. var previousCamera = null;
  8808. if (scene.activeCamera !== camera) {
  8809. previousCamera = scene.activeCamera;
  8810. scene.activeCamera = camera;
  8811. }
  8812. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8813. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8814. texture.renderList = null;
  8815. texture.samples = samples;
  8816. if (antialiasing) {
  8817. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8818. }
  8819. texture.onAfterRenderObservable.add(function () {
  8820. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8821. });
  8822. scene.incrementRenderId();
  8823. scene.resetCachedMaterial();
  8824. texture.render(true);
  8825. texture.dispose();
  8826. if (previousCamera) {
  8827. scene.activeCamera = previousCamera;
  8828. }
  8829. camera.getProjectionMatrix(true); // Force cache refresh;
  8830. };
  8831. // XHR response validator for local file scenario
  8832. Tools.ValidateXHRData = function (xhr, dataType) {
  8833. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8834. if (dataType === void 0) { dataType = 7; }
  8835. try {
  8836. if (dataType & 1) {
  8837. if (xhr.responseText && xhr.responseText.length > 0) {
  8838. return true;
  8839. }
  8840. else if (dataType === 1) {
  8841. return false;
  8842. }
  8843. }
  8844. if (dataType & 2) {
  8845. // Check header width and height since there is no "TGA" magic number
  8846. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8847. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8848. return true;
  8849. }
  8850. else if (dataType === 2) {
  8851. return false;
  8852. }
  8853. }
  8854. if (dataType & 4) {
  8855. // Check for the "DDS" magic number
  8856. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8857. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8858. return true;
  8859. }
  8860. else {
  8861. return false;
  8862. }
  8863. }
  8864. }
  8865. catch (e) {
  8866. // Global protection
  8867. }
  8868. return false;
  8869. };
  8870. /**
  8871. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8872. * Be aware Math.random() could cause collisions, but:
  8873. * "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"
  8874. */
  8875. Tools.RandomId = function () {
  8876. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8877. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8878. return v.toString(16);
  8879. });
  8880. };
  8881. /**
  8882. * Test if the given uri is a base64 string.
  8883. * @param uri The uri to test
  8884. * @return True if the uri is a base64 string or false otherwise.
  8885. */
  8886. Tools.IsBase64 = function (uri) {
  8887. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8888. };
  8889. /**
  8890. * Decode the given base64 uri.
  8891. * @param uri The uri to decode
  8892. * @return The decoded base64 data.
  8893. */
  8894. Tools.DecodeBase64 = function (uri) {
  8895. var decodedString = atob(uri.split(",")[1]);
  8896. var bufferLength = decodedString.length;
  8897. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8898. for (var i = 0; i < bufferLength; i++) {
  8899. bufferView[i] = decodedString.charCodeAt(i);
  8900. }
  8901. return bufferView.buffer;
  8902. };
  8903. Object.defineProperty(Tools, "NoneLogLevel", {
  8904. get: function () {
  8905. return Tools._NoneLogLevel;
  8906. },
  8907. enumerable: true,
  8908. configurable: true
  8909. });
  8910. Object.defineProperty(Tools, "MessageLogLevel", {
  8911. get: function () {
  8912. return Tools._MessageLogLevel;
  8913. },
  8914. enumerable: true,
  8915. configurable: true
  8916. });
  8917. Object.defineProperty(Tools, "WarningLogLevel", {
  8918. get: function () {
  8919. return Tools._WarningLogLevel;
  8920. },
  8921. enumerable: true,
  8922. configurable: true
  8923. });
  8924. Object.defineProperty(Tools, "ErrorLogLevel", {
  8925. get: function () {
  8926. return Tools._ErrorLogLevel;
  8927. },
  8928. enumerable: true,
  8929. configurable: true
  8930. });
  8931. Object.defineProperty(Tools, "AllLogLevel", {
  8932. get: function () {
  8933. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8934. },
  8935. enumerable: true,
  8936. configurable: true
  8937. });
  8938. Tools._AddLogEntry = function (entry) {
  8939. Tools._LogCache = entry + Tools._LogCache;
  8940. if (Tools.OnNewCacheEntry) {
  8941. Tools.OnNewCacheEntry(entry);
  8942. }
  8943. };
  8944. Tools._FormatMessage = function (message) {
  8945. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8946. var date = new Date();
  8947. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8948. };
  8949. Tools._LogDisabled = function (message) {
  8950. // nothing to do
  8951. };
  8952. Tools._LogEnabled = function (message) {
  8953. var formattedMessage = Tools._FormatMessage(message);
  8954. console.log("BJS - " + formattedMessage);
  8955. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8956. Tools._AddLogEntry(entry);
  8957. };
  8958. Tools._WarnDisabled = function (message) {
  8959. // nothing to do
  8960. };
  8961. Tools._WarnEnabled = function (message) {
  8962. var formattedMessage = Tools._FormatMessage(message);
  8963. console.warn("BJS - " + formattedMessage);
  8964. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8965. Tools._AddLogEntry(entry);
  8966. };
  8967. Tools._ErrorDisabled = function (message) {
  8968. // nothing to do
  8969. };
  8970. Tools._ErrorEnabled = function (message) {
  8971. Tools.errorsCount++;
  8972. var formattedMessage = Tools._FormatMessage(message);
  8973. console.error("BJS - " + formattedMessage);
  8974. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8975. Tools._AddLogEntry(entry);
  8976. };
  8977. Object.defineProperty(Tools, "LogCache", {
  8978. get: function () {
  8979. return Tools._LogCache;
  8980. },
  8981. enumerable: true,
  8982. configurable: true
  8983. });
  8984. Tools.ClearLogCache = function () {
  8985. Tools._LogCache = "";
  8986. Tools.errorsCount = 0;
  8987. };
  8988. Object.defineProperty(Tools, "LogLevels", {
  8989. set: function (level) {
  8990. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8991. Tools.Log = Tools._LogEnabled;
  8992. }
  8993. else {
  8994. Tools.Log = Tools._LogDisabled;
  8995. }
  8996. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8997. Tools.Warn = Tools._WarnEnabled;
  8998. }
  8999. else {
  9000. Tools.Warn = Tools._WarnDisabled;
  9001. }
  9002. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9003. Tools.Error = Tools._ErrorEnabled;
  9004. }
  9005. else {
  9006. Tools.Error = Tools._ErrorDisabled;
  9007. }
  9008. },
  9009. enumerable: true,
  9010. configurable: true
  9011. });
  9012. Tools.IsWindowObjectExist = function () {
  9013. return (typeof window) !== "undefined";
  9014. };
  9015. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9016. get: function () {
  9017. return Tools._PerformanceNoneLogLevel;
  9018. },
  9019. enumerable: true,
  9020. configurable: true
  9021. });
  9022. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9023. get: function () {
  9024. return Tools._PerformanceUserMarkLogLevel;
  9025. },
  9026. enumerable: true,
  9027. configurable: true
  9028. });
  9029. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9030. get: function () {
  9031. return Tools._PerformanceConsoleLogLevel;
  9032. },
  9033. enumerable: true,
  9034. configurable: true
  9035. });
  9036. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9037. set: function (level) {
  9038. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9039. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9040. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9041. return;
  9042. }
  9043. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9044. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9045. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9046. return;
  9047. }
  9048. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9049. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9050. },
  9051. enumerable: true,
  9052. configurable: true
  9053. });
  9054. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9055. };
  9056. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9057. };
  9058. Tools._StartUserMark = function (counterName, condition) {
  9059. if (condition === void 0) { condition = true; }
  9060. if (!Tools._performance) {
  9061. if (!Tools.IsWindowObjectExist()) {
  9062. return;
  9063. }
  9064. Tools._performance = window.performance;
  9065. }
  9066. if (!condition || !Tools._performance.mark) {
  9067. return;
  9068. }
  9069. Tools._performance.mark(counterName + "-Begin");
  9070. };
  9071. Tools._EndUserMark = function (counterName, condition) {
  9072. if (condition === void 0) { condition = true; }
  9073. if (!condition || !Tools._performance.mark) {
  9074. return;
  9075. }
  9076. Tools._performance.mark(counterName + "-End");
  9077. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9078. };
  9079. Tools._StartPerformanceConsole = function (counterName, condition) {
  9080. if (condition === void 0) { condition = true; }
  9081. if (!condition) {
  9082. return;
  9083. }
  9084. Tools._StartUserMark(counterName, condition);
  9085. if (console.time) {
  9086. console.time(counterName);
  9087. }
  9088. };
  9089. Tools._EndPerformanceConsole = function (counterName, condition) {
  9090. if (condition === void 0) { condition = true; }
  9091. if (!condition) {
  9092. return;
  9093. }
  9094. Tools._EndUserMark(counterName, condition);
  9095. if (console.time) {
  9096. console.timeEnd(counterName);
  9097. }
  9098. };
  9099. Object.defineProperty(Tools, "Now", {
  9100. get: function () {
  9101. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9102. return window.performance.now();
  9103. }
  9104. return new Date().getTime();
  9105. },
  9106. enumerable: true,
  9107. configurable: true
  9108. });
  9109. /**
  9110. * This method will return the name of the class used to create the instance of the given object.
  9111. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9112. * @param object the object to get the class name from
  9113. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9114. */
  9115. Tools.GetClassName = function (object, isType) {
  9116. if (isType === void 0) { isType = false; }
  9117. var name = null;
  9118. if (!isType && object.getClassName) {
  9119. name = object.getClassName();
  9120. }
  9121. else {
  9122. if (object instanceof Object) {
  9123. var classObj = isType ? object : Object.getPrototypeOf(object);
  9124. name = classObj.constructor["__bjsclassName__"];
  9125. }
  9126. if (!name) {
  9127. name = typeof object;
  9128. }
  9129. }
  9130. return name;
  9131. };
  9132. Tools.First = function (array, predicate) {
  9133. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9134. var el = array_1[_i];
  9135. if (predicate(el)) {
  9136. return el;
  9137. }
  9138. }
  9139. return null;
  9140. };
  9141. /**
  9142. * This method will return the name of the full name of the class, including its owning module (if any).
  9143. * 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).
  9144. * @param object the object to get the class name from
  9145. * @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.
  9146. */
  9147. Tools.getFullClassName = function (object, isType) {
  9148. if (isType === void 0) { isType = false; }
  9149. var className = null;
  9150. var moduleName = null;
  9151. if (!isType && object.getClassName) {
  9152. className = object.getClassName();
  9153. }
  9154. else {
  9155. if (object instanceof Object) {
  9156. var classObj = isType ? object : Object.getPrototypeOf(object);
  9157. className = classObj.constructor["__bjsclassName__"];
  9158. moduleName = classObj.constructor["__bjsmoduleName__"];
  9159. }
  9160. if (!className) {
  9161. className = typeof object;
  9162. }
  9163. }
  9164. if (!className) {
  9165. return null;
  9166. }
  9167. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9168. };
  9169. /**
  9170. * 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.
  9171. * @param array
  9172. */
  9173. Tools.arrayOrStringFeeder = function (array) {
  9174. return function (index) {
  9175. if (index >= array.length) {
  9176. return null;
  9177. }
  9178. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9179. if (val && val.getHashCode) {
  9180. val = val.getHashCode();
  9181. }
  9182. if (typeof val === "string") {
  9183. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9184. }
  9185. return val;
  9186. };
  9187. };
  9188. /**
  9189. * Compute the hashCode of a stream of number
  9190. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9191. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9192. * @return the hash code computed
  9193. */
  9194. Tools.hashCodeFromStream = function (feeder) {
  9195. // Based from here: http://stackoverflow.com/a/7616484/802124
  9196. var hash = 0;
  9197. var index = 0;
  9198. var chr = feeder(index++);
  9199. while (chr != null) {
  9200. hash = ((hash << 5) - hash) + chr;
  9201. hash |= 0; // Convert to 32bit integer
  9202. chr = feeder(index++);
  9203. }
  9204. return hash;
  9205. };
  9206. /**
  9207. * Returns a promise that resolves after the given amount of time.
  9208. * @param delay Number of milliseconds to delay
  9209. * @returns Promise that resolves after the given amount of time
  9210. */
  9211. Tools.DelayAsync = function (delay) {
  9212. return new Promise(function (resolve) {
  9213. setTimeout(function () {
  9214. resolve();
  9215. }, delay);
  9216. });
  9217. };
  9218. Tools.BaseUrl = "";
  9219. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9220. /**
  9221. * Default behaviour for cors in the application.
  9222. * It can be a string if the expected behavior is identical in the entire app.
  9223. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9224. */
  9225. Tools.CorsBehavior = "anonymous";
  9226. Tools.UseFallbackTexture = true;
  9227. /**
  9228. * Use this object to register external classes like custom textures or material
  9229. * to allow the laoders to instantiate them
  9230. */
  9231. Tools.RegisteredExternalClasses = {};
  9232. // Used in case of a texture loading problem
  9233. 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";
  9234. Tools.PreprocessUrl = function (url) {
  9235. return url;
  9236. };
  9237. // Logs
  9238. Tools._NoneLogLevel = 0;
  9239. Tools._MessageLogLevel = 1;
  9240. Tools._WarningLogLevel = 2;
  9241. Tools._ErrorLogLevel = 4;
  9242. Tools._LogCache = "";
  9243. Tools.errorsCount = 0;
  9244. Tools.Log = Tools._LogEnabled;
  9245. Tools.Warn = Tools._WarnEnabled;
  9246. Tools.Error = Tools._ErrorEnabled;
  9247. // Performances
  9248. Tools._PerformanceNoneLogLevel = 0;
  9249. Tools._PerformanceUserMarkLogLevel = 1;
  9250. Tools._PerformanceConsoleLogLevel = 2;
  9251. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9252. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9253. return Tools;
  9254. }());
  9255. BABYLON.Tools = Tools;
  9256. /**
  9257. * This class is used to track a performance counter which is number based.
  9258. * The user has access to many properties which give statistics of different nature
  9259. *
  9260. * The implementer can track two kinds of Performance Counter: time and count
  9261. * 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.
  9262. * 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.
  9263. */
  9264. var PerfCounter = /** @class */ (function () {
  9265. function PerfCounter() {
  9266. this._startMonitoringTime = 0;
  9267. this._min = 0;
  9268. this._max = 0;
  9269. this._average = 0;
  9270. this._lastSecAverage = 0;
  9271. this._current = 0;
  9272. this._totalValueCount = 0;
  9273. this._totalAccumulated = 0;
  9274. this._lastSecAccumulated = 0;
  9275. this._lastSecTime = 0;
  9276. this._lastSecValueCount = 0;
  9277. }
  9278. Object.defineProperty(PerfCounter.prototype, "min", {
  9279. /**
  9280. * Returns the smallest value ever
  9281. */
  9282. get: function () {
  9283. return this._min;
  9284. },
  9285. enumerable: true,
  9286. configurable: true
  9287. });
  9288. Object.defineProperty(PerfCounter.prototype, "max", {
  9289. /**
  9290. * Returns the biggest value ever
  9291. */
  9292. get: function () {
  9293. return this._max;
  9294. },
  9295. enumerable: true,
  9296. configurable: true
  9297. });
  9298. Object.defineProperty(PerfCounter.prototype, "average", {
  9299. /**
  9300. * Returns the average value since the performance counter is running
  9301. */
  9302. get: function () {
  9303. return this._average;
  9304. },
  9305. enumerable: true,
  9306. configurable: true
  9307. });
  9308. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9309. /**
  9310. * Returns the average value of the last second the counter was monitored
  9311. */
  9312. get: function () {
  9313. return this._lastSecAverage;
  9314. },
  9315. enumerable: true,
  9316. configurable: true
  9317. });
  9318. Object.defineProperty(PerfCounter.prototype, "current", {
  9319. /**
  9320. * Returns the current value
  9321. */
  9322. get: function () {
  9323. return this._current;
  9324. },
  9325. enumerable: true,
  9326. configurable: true
  9327. });
  9328. Object.defineProperty(PerfCounter.prototype, "total", {
  9329. get: function () {
  9330. return this._totalAccumulated;
  9331. },
  9332. enumerable: true,
  9333. configurable: true
  9334. });
  9335. Object.defineProperty(PerfCounter.prototype, "count", {
  9336. get: function () {
  9337. return this._totalValueCount;
  9338. },
  9339. enumerable: true,
  9340. configurable: true
  9341. });
  9342. /**
  9343. * Call this method to start monitoring a new frame.
  9344. * 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.
  9345. */
  9346. PerfCounter.prototype.fetchNewFrame = function () {
  9347. this._totalValueCount++;
  9348. this._current = 0;
  9349. this._lastSecValueCount++;
  9350. };
  9351. /**
  9352. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9353. * @param newCount the count value to add to the monitored count
  9354. * @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.
  9355. */
  9356. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9357. if (!PerfCounter.Enabled) {
  9358. return;
  9359. }
  9360. this._current += newCount;
  9361. if (fetchResult) {
  9362. this._fetchResult();
  9363. }
  9364. };
  9365. /**
  9366. * Start monitoring this performance counter
  9367. */
  9368. PerfCounter.prototype.beginMonitoring = function () {
  9369. if (!PerfCounter.Enabled) {
  9370. return;
  9371. }
  9372. this._startMonitoringTime = Tools.Now;
  9373. };
  9374. /**
  9375. * Compute the time lapsed since the previous beginMonitoring() call.
  9376. * @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
  9377. */
  9378. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9379. if (newFrame === void 0) { newFrame = true; }
  9380. if (!PerfCounter.Enabled) {
  9381. return;
  9382. }
  9383. if (newFrame) {
  9384. this.fetchNewFrame();
  9385. }
  9386. var currentTime = Tools.Now;
  9387. this._current = currentTime - this._startMonitoringTime;
  9388. if (newFrame) {
  9389. this._fetchResult();
  9390. }
  9391. };
  9392. PerfCounter.prototype._fetchResult = function () {
  9393. this._totalAccumulated += this._current;
  9394. this._lastSecAccumulated += this._current;
  9395. // Min/Max update
  9396. this._min = Math.min(this._min, this._current);
  9397. this._max = Math.max(this._max, this._current);
  9398. this._average = this._totalAccumulated / this._totalValueCount;
  9399. // Reset last sec?
  9400. var now = Tools.Now;
  9401. if ((now - this._lastSecTime) > 1000) {
  9402. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9403. this._lastSecTime = now;
  9404. this._lastSecAccumulated = 0;
  9405. this._lastSecValueCount = 0;
  9406. }
  9407. };
  9408. PerfCounter.Enabled = true;
  9409. return PerfCounter;
  9410. }());
  9411. BABYLON.PerfCounter = PerfCounter;
  9412. /**
  9413. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9414. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9415. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9416. * @param name The name of the class, case should be preserved
  9417. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9418. */
  9419. function className(name, module) {
  9420. return function (target) {
  9421. target["__bjsclassName__"] = name;
  9422. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9423. };
  9424. }
  9425. BABYLON.className = className;
  9426. /**
  9427. * An implementation of a loop for asynchronous functions.
  9428. */
  9429. var AsyncLoop = /** @class */ (function () {
  9430. /**
  9431. * Constroctor.
  9432. * @param iterations the number of iterations.
  9433. * @param _fn the function to run each iteration
  9434. * @param _successCallback the callback that will be called upon succesful execution
  9435. * @param offset starting offset.
  9436. */
  9437. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9438. if (offset === void 0) { offset = 0; }
  9439. this.iterations = iterations;
  9440. this._fn = _fn;
  9441. this._successCallback = _successCallback;
  9442. this.index = offset - 1;
  9443. this._done = false;
  9444. }
  9445. /**
  9446. * Execute the next iteration. Must be called after the last iteration was finished.
  9447. */
  9448. AsyncLoop.prototype.executeNext = function () {
  9449. if (!this._done) {
  9450. if (this.index + 1 < this.iterations) {
  9451. ++this.index;
  9452. this._fn(this);
  9453. }
  9454. else {
  9455. this.breakLoop();
  9456. }
  9457. }
  9458. };
  9459. /**
  9460. * Break the loop and run the success callback.
  9461. */
  9462. AsyncLoop.prototype.breakLoop = function () {
  9463. this._done = true;
  9464. this._successCallback();
  9465. };
  9466. /**
  9467. * Helper function
  9468. */
  9469. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9470. if (offset === void 0) { offset = 0; }
  9471. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9472. loop.executeNext();
  9473. return loop;
  9474. };
  9475. /**
  9476. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9477. * @param iterations total number of iterations
  9478. * @param syncedIterations number of synchronous iterations in each async iteration.
  9479. * @param fn the function to call each iteration.
  9480. * @param callback a success call back that will be called when iterating stops.
  9481. * @param breakFunction a break condition (optional)
  9482. * @param timeout timeout settings for the setTimeout function. default - 0.
  9483. * @constructor
  9484. */
  9485. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9486. if (timeout === void 0) { timeout = 0; }
  9487. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9488. if (breakFunction && breakFunction())
  9489. loop.breakLoop();
  9490. else {
  9491. setTimeout(function () {
  9492. for (var i = 0; i < syncedIterations; ++i) {
  9493. var iteration = (loop.index * syncedIterations) + i;
  9494. if (iteration >= iterations)
  9495. break;
  9496. fn(iteration);
  9497. if (breakFunction && breakFunction()) {
  9498. loop.breakLoop();
  9499. break;
  9500. }
  9501. }
  9502. loop.executeNext();
  9503. }, timeout);
  9504. }
  9505. }, callback);
  9506. };
  9507. return AsyncLoop;
  9508. }());
  9509. BABYLON.AsyncLoop = AsyncLoop;
  9510. })(BABYLON || (BABYLON = {}));
  9511. //# sourceMappingURL=babylon.tools.js.map
  9512. "use strict";
  9513. var BABYLON;
  9514. (function (BABYLON) {
  9515. var PromiseStates;
  9516. (function (PromiseStates) {
  9517. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9518. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9519. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9520. })(PromiseStates || (PromiseStates = {}));
  9521. var FulFillmentAgregator = /** @class */ (function () {
  9522. function FulFillmentAgregator() {
  9523. this.count = 0;
  9524. this.target = 0;
  9525. this.results = [];
  9526. }
  9527. return FulFillmentAgregator;
  9528. }());
  9529. var InternalPromise = /** @class */ (function () {
  9530. function InternalPromise(resolver) {
  9531. var _this = this;
  9532. this._state = PromiseStates.Pending;
  9533. this._children = new Array();
  9534. this._rejectWasConsumed = false;
  9535. if (!resolver) {
  9536. return;
  9537. }
  9538. try {
  9539. resolver(function (value) {
  9540. _this._resolve(value);
  9541. }, function (reason) {
  9542. _this._reject(reason);
  9543. });
  9544. }
  9545. catch (e) {
  9546. this._reject(e);
  9547. }
  9548. }
  9549. InternalPromise.prototype.catch = function (onRejected) {
  9550. return this.then(undefined, onRejected);
  9551. };
  9552. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9553. var _this = this;
  9554. var newPromise = new InternalPromise();
  9555. newPromise._onFulfilled = onFulfilled;
  9556. newPromise._onRejected = onRejected;
  9557. // Composition
  9558. this._children.push(newPromise);
  9559. if (this._state !== PromiseStates.Pending) {
  9560. BABYLON.Tools.SetImmediate(function () {
  9561. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9562. var returnedValue = newPromise._resolve(_this._result);
  9563. if (returnedValue !== undefined && returnedValue !== null) {
  9564. if (returnedValue._state !== undefined) {
  9565. var returnedPromise = returnedValue;
  9566. newPromise._children.push(returnedPromise);
  9567. newPromise = returnedPromise;
  9568. }
  9569. else {
  9570. newPromise._result = returnedValue;
  9571. }
  9572. }
  9573. }
  9574. else {
  9575. newPromise._reject(_this._reason);
  9576. }
  9577. });
  9578. }
  9579. return newPromise;
  9580. };
  9581. InternalPromise.prototype._moveChildren = function (children) {
  9582. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9583. if (this._state === PromiseStates.Fulfilled) {
  9584. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9585. var child = _b[_i];
  9586. child._resolve(this._result);
  9587. }
  9588. }
  9589. else if (this._state === PromiseStates.Rejected) {
  9590. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9591. var child = _d[_c];
  9592. child._reject(this._reason);
  9593. }
  9594. }
  9595. var _a;
  9596. };
  9597. InternalPromise.prototype._resolve = function (value) {
  9598. try {
  9599. this._state = PromiseStates.Fulfilled;
  9600. this._result = value;
  9601. var returnedValue = null;
  9602. if (this._onFulfilled) {
  9603. returnedValue = this._onFulfilled(value);
  9604. }
  9605. if (returnedValue !== undefined && returnedValue !== null) {
  9606. if (returnedValue._state !== undefined) {
  9607. // Transmit children
  9608. var returnedPromise = returnedValue;
  9609. returnedPromise._moveChildren(this._children);
  9610. }
  9611. else {
  9612. value = returnedValue;
  9613. }
  9614. }
  9615. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9616. var child = _a[_i];
  9617. child._resolve(value);
  9618. }
  9619. this._children.length = 0;
  9620. delete this._onFulfilled;
  9621. delete this._onRejected;
  9622. return returnedValue;
  9623. }
  9624. catch (e) {
  9625. this._reject(e, true);
  9626. }
  9627. return null;
  9628. };
  9629. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9630. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9631. this._state = PromiseStates.Rejected;
  9632. this._reason = reason;
  9633. if (this._onRejected && !onLocalThrow) {
  9634. try {
  9635. this._onRejected(reason);
  9636. this._rejectWasConsumed = true;
  9637. }
  9638. catch (e) {
  9639. reason = e;
  9640. }
  9641. }
  9642. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9643. var child = _a[_i];
  9644. if (this._rejectWasConsumed) {
  9645. child._resolve(null);
  9646. }
  9647. else {
  9648. child._reject(reason);
  9649. }
  9650. }
  9651. this._children.length = 0;
  9652. delete this._onFulfilled;
  9653. delete this._onRejected;
  9654. };
  9655. InternalPromise.resolve = function (value) {
  9656. var newPromise = new InternalPromise();
  9657. newPromise._resolve(value);
  9658. return newPromise;
  9659. };
  9660. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9661. promise.then(function (value) {
  9662. agregator.results[index] = value;
  9663. agregator.count++;
  9664. if (agregator.count === agregator.target) {
  9665. agregator.rootPromise._resolve(agregator.results);
  9666. }
  9667. return null;
  9668. }, function (reason) {
  9669. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9670. agregator.rootPromise._reject(reason);
  9671. }
  9672. });
  9673. };
  9674. InternalPromise.all = function (promises) {
  9675. var newPromise = new InternalPromise();
  9676. var agregator = new FulFillmentAgregator();
  9677. agregator.target = promises.length;
  9678. agregator.rootPromise = newPromise;
  9679. if (promises.length) {
  9680. for (var index = 0; index < promises.length; index++) {
  9681. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9682. }
  9683. }
  9684. else {
  9685. newPromise._resolve([]);
  9686. }
  9687. return newPromise;
  9688. };
  9689. InternalPromise.race = function (promises) {
  9690. var newPromise = new InternalPromise();
  9691. if (promises.length) {
  9692. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9693. var promise = promises_1[_i];
  9694. promise.then(function (value) {
  9695. if (newPromise) {
  9696. newPromise._resolve(value);
  9697. newPromise = null;
  9698. }
  9699. return null;
  9700. }, function (reason) {
  9701. if (newPromise) {
  9702. newPromise._reject(reason);
  9703. newPromise = null;
  9704. }
  9705. });
  9706. }
  9707. }
  9708. return newPromise;
  9709. };
  9710. return InternalPromise;
  9711. }());
  9712. /**
  9713. * Helper class that provides a small promise polyfill
  9714. */
  9715. var PromisePolyfill = /** @class */ (function () {
  9716. function PromisePolyfill() {
  9717. }
  9718. /**
  9719. * Static function used to check if the polyfill is required
  9720. * If this is the case then the function will inject the polyfill to window.Promise
  9721. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9722. */
  9723. PromisePolyfill.Apply = function (force) {
  9724. if (force === void 0) { force = false; }
  9725. if (force || typeof Promise === 'undefined') {
  9726. var root = window;
  9727. root.Promise = InternalPromise;
  9728. }
  9729. };
  9730. return PromisePolyfill;
  9731. }());
  9732. BABYLON.PromisePolyfill = PromisePolyfill;
  9733. })(BABYLON || (BABYLON = {}));
  9734. //# sourceMappingURL=babylon.promise.js.map
  9735. "use strict";
  9736. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9737. var BABYLON;
  9738. (function (BABYLON) {
  9739. /**
  9740. * Helper class to push actions to a pool of workers.
  9741. */
  9742. var WorkerPool = /** @class */ (function () {
  9743. /**
  9744. * Constructor
  9745. * @param workers Array of workers to use for actions
  9746. */
  9747. function WorkerPool(workers) {
  9748. this._pendingActions = new Array();
  9749. this._workerInfos = workers.map(function (worker) { return ({
  9750. worker: worker,
  9751. active: false
  9752. }); });
  9753. }
  9754. /**
  9755. * Terminates all workers and clears any pending actions.
  9756. */
  9757. WorkerPool.prototype.dispose = function () {
  9758. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9759. var workerInfo = _a[_i];
  9760. workerInfo.worker.terminate();
  9761. }
  9762. delete this._workerInfos;
  9763. delete this._pendingActions;
  9764. };
  9765. /**
  9766. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9767. * pended until a worker has completed its action.
  9768. * @param action The action to perform. Call onComplete when the action is complete.
  9769. */
  9770. WorkerPool.prototype.push = function (action) {
  9771. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9772. var workerInfo = _a[_i];
  9773. if (!workerInfo.active) {
  9774. this._execute(workerInfo, action);
  9775. return;
  9776. }
  9777. }
  9778. this._pendingActions.push(action);
  9779. };
  9780. WorkerPool.prototype._execute = function (workerInfo, action) {
  9781. var _this = this;
  9782. workerInfo.active = true;
  9783. action(workerInfo.worker, function () {
  9784. workerInfo.active = false;
  9785. var nextAction = _this._pendingActions.shift();
  9786. if (nextAction) {
  9787. _this._execute(workerInfo, nextAction);
  9788. }
  9789. });
  9790. };
  9791. return WorkerPool;
  9792. }());
  9793. BABYLON.WorkerPool = WorkerPool;
  9794. })(BABYLON || (BABYLON = {}));
  9795. //# sourceMappingURL=babylon.workerPool.js.map
  9796. "use strict";
  9797. var BABYLON;
  9798. (function (BABYLON) {
  9799. var _AlphaState = /** @class */ (function () {
  9800. /**
  9801. * Initializes the state.
  9802. */
  9803. function _AlphaState() {
  9804. this._isAlphaBlendDirty = false;
  9805. this._isBlendFunctionParametersDirty = false;
  9806. this._isBlendEquationParametersDirty = false;
  9807. this._isBlendConstantsDirty = false;
  9808. this._alphaBlend = false;
  9809. this._blendFunctionParameters = new Array(4);
  9810. this._blendEquationParameters = new Array(2);
  9811. this._blendConstants = new Array(4);
  9812. this.reset();
  9813. }
  9814. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9815. get: function () {
  9816. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9817. },
  9818. enumerable: true,
  9819. configurable: true
  9820. });
  9821. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9822. get: function () {
  9823. return this._alphaBlend;
  9824. },
  9825. set: function (value) {
  9826. if (this._alphaBlend === value) {
  9827. return;
  9828. }
  9829. this._alphaBlend = value;
  9830. this._isAlphaBlendDirty = true;
  9831. },
  9832. enumerable: true,
  9833. configurable: true
  9834. });
  9835. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9836. if (this._blendConstants[0] === r &&
  9837. this._blendConstants[1] === g &&
  9838. this._blendConstants[2] === b &&
  9839. this._blendConstants[3] === a) {
  9840. return;
  9841. }
  9842. this._blendConstants[0] = r;
  9843. this._blendConstants[1] = g;
  9844. this._blendConstants[2] = b;
  9845. this._blendConstants[3] = a;
  9846. this._isBlendConstantsDirty = true;
  9847. };
  9848. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9849. if (this._blendFunctionParameters[0] === value0 &&
  9850. this._blendFunctionParameters[1] === value1 &&
  9851. this._blendFunctionParameters[2] === value2 &&
  9852. this._blendFunctionParameters[3] === value3) {
  9853. return;
  9854. }
  9855. this._blendFunctionParameters[0] = value0;
  9856. this._blendFunctionParameters[1] = value1;
  9857. this._blendFunctionParameters[2] = value2;
  9858. this._blendFunctionParameters[3] = value3;
  9859. this._isBlendFunctionParametersDirty = true;
  9860. };
  9861. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9862. if (this._blendEquationParameters[0] === rgb &&
  9863. this._blendEquationParameters[1] === alpha) {
  9864. return;
  9865. }
  9866. this._blendEquationParameters[0] = rgb;
  9867. this._blendEquationParameters[1] = alpha;
  9868. this._isBlendEquationParametersDirty = true;
  9869. };
  9870. _AlphaState.prototype.reset = function () {
  9871. this._alphaBlend = false;
  9872. this._blendFunctionParameters[0] = null;
  9873. this._blendFunctionParameters[1] = null;
  9874. this._blendFunctionParameters[2] = null;
  9875. this._blendFunctionParameters[3] = null;
  9876. this._blendEquationParameters[0] = null;
  9877. this._blendEquationParameters[1] = null;
  9878. this._blendConstants[0] = null;
  9879. this._blendConstants[1] = null;
  9880. this._blendConstants[2] = null;
  9881. this._blendConstants[3] = null;
  9882. this._isAlphaBlendDirty = true;
  9883. this._isBlendFunctionParametersDirty = false;
  9884. this._isBlendEquationParametersDirty = false;
  9885. this._isBlendConstantsDirty = false;
  9886. };
  9887. _AlphaState.prototype.apply = function (gl) {
  9888. if (!this.isDirty) {
  9889. return;
  9890. }
  9891. // Alpha blend
  9892. if (this._isAlphaBlendDirty) {
  9893. if (this._alphaBlend) {
  9894. gl.enable(gl.BLEND);
  9895. }
  9896. else {
  9897. gl.disable(gl.BLEND);
  9898. }
  9899. this._isAlphaBlendDirty = false;
  9900. }
  9901. // Alpha function
  9902. if (this._isBlendFunctionParametersDirty) {
  9903. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9904. this._isBlendFunctionParametersDirty = false;
  9905. }
  9906. // Alpha equation
  9907. if (this._isBlendEquationParametersDirty) {
  9908. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9909. this._isBlendEquationParametersDirty = false;
  9910. }
  9911. // Constants
  9912. if (this._isBlendConstantsDirty) {
  9913. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9914. this._isBlendConstantsDirty = false;
  9915. }
  9916. };
  9917. return _AlphaState;
  9918. }());
  9919. BABYLON._AlphaState = _AlphaState;
  9920. })(BABYLON || (BABYLON = {}));
  9921. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9922. "use strict";
  9923. var BABYLON;
  9924. (function (BABYLON) {
  9925. var _DepthCullingState = /** @class */ (function () {
  9926. /**
  9927. * Initializes the state.
  9928. */
  9929. function _DepthCullingState() {
  9930. this._isDepthTestDirty = false;
  9931. this._isDepthMaskDirty = false;
  9932. this._isDepthFuncDirty = false;
  9933. this._isCullFaceDirty = false;
  9934. this._isCullDirty = false;
  9935. this._isZOffsetDirty = false;
  9936. this._isFrontFaceDirty = false;
  9937. this.reset();
  9938. }
  9939. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9940. get: function () {
  9941. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9942. },
  9943. enumerable: true,
  9944. configurable: true
  9945. });
  9946. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9947. get: function () {
  9948. return this._zOffset;
  9949. },
  9950. set: function (value) {
  9951. if (this._zOffset === value) {
  9952. return;
  9953. }
  9954. this._zOffset = value;
  9955. this._isZOffsetDirty = true;
  9956. },
  9957. enumerable: true,
  9958. configurable: true
  9959. });
  9960. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9961. get: function () {
  9962. return this._cullFace;
  9963. },
  9964. set: function (value) {
  9965. if (this._cullFace === value) {
  9966. return;
  9967. }
  9968. this._cullFace = value;
  9969. this._isCullFaceDirty = true;
  9970. },
  9971. enumerable: true,
  9972. configurable: true
  9973. });
  9974. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9975. get: function () {
  9976. return this._cull;
  9977. },
  9978. set: function (value) {
  9979. if (this._cull === value) {
  9980. return;
  9981. }
  9982. this._cull = value;
  9983. this._isCullDirty = true;
  9984. },
  9985. enumerable: true,
  9986. configurable: true
  9987. });
  9988. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9989. get: function () {
  9990. return this._depthFunc;
  9991. },
  9992. set: function (value) {
  9993. if (this._depthFunc === value) {
  9994. return;
  9995. }
  9996. this._depthFunc = value;
  9997. this._isDepthFuncDirty = true;
  9998. },
  9999. enumerable: true,
  10000. configurable: true
  10001. });
  10002. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10003. get: function () {
  10004. return this._depthMask;
  10005. },
  10006. set: function (value) {
  10007. if (this._depthMask === value) {
  10008. return;
  10009. }
  10010. this._depthMask = value;
  10011. this._isDepthMaskDirty = true;
  10012. },
  10013. enumerable: true,
  10014. configurable: true
  10015. });
  10016. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10017. get: function () {
  10018. return this._depthTest;
  10019. },
  10020. set: function (value) {
  10021. if (this._depthTest === value) {
  10022. return;
  10023. }
  10024. this._depthTest = value;
  10025. this._isDepthTestDirty = true;
  10026. },
  10027. enumerable: true,
  10028. configurable: true
  10029. });
  10030. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10031. get: function () {
  10032. return this._frontFace;
  10033. },
  10034. set: function (value) {
  10035. if (this._frontFace === value) {
  10036. return;
  10037. }
  10038. this._frontFace = value;
  10039. this._isFrontFaceDirty = true;
  10040. },
  10041. enumerable: true,
  10042. configurable: true
  10043. });
  10044. _DepthCullingState.prototype.reset = function () {
  10045. this._depthMask = true;
  10046. this._depthTest = true;
  10047. this._depthFunc = null;
  10048. this._cullFace = null;
  10049. this._cull = null;
  10050. this._zOffset = 0;
  10051. this._frontFace = null;
  10052. this._isDepthTestDirty = true;
  10053. this._isDepthMaskDirty = true;
  10054. this._isDepthFuncDirty = false;
  10055. this._isCullFaceDirty = false;
  10056. this._isCullDirty = false;
  10057. this._isZOffsetDirty = false;
  10058. this._isFrontFaceDirty = false;
  10059. };
  10060. _DepthCullingState.prototype.apply = function (gl) {
  10061. if (!this.isDirty) {
  10062. return;
  10063. }
  10064. // Cull
  10065. if (this._isCullDirty) {
  10066. if (this.cull) {
  10067. gl.enable(gl.CULL_FACE);
  10068. }
  10069. else {
  10070. gl.disable(gl.CULL_FACE);
  10071. }
  10072. this._isCullDirty = false;
  10073. }
  10074. // Cull face
  10075. if (this._isCullFaceDirty) {
  10076. gl.cullFace(this.cullFace);
  10077. this._isCullFaceDirty = false;
  10078. }
  10079. // Depth mask
  10080. if (this._isDepthMaskDirty) {
  10081. gl.depthMask(this.depthMask);
  10082. this._isDepthMaskDirty = false;
  10083. }
  10084. // Depth test
  10085. if (this._isDepthTestDirty) {
  10086. if (this.depthTest) {
  10087. gl.enable(gl.DEPTH_TEST);
  10088. }
  10089. else {
  10090. gl.disable(gl.DEPTH_TEST);
  10091. }
  10092. this._isDepthTestDirty = false;
  10093. }
  10094. // Depth func
  10095. if (this._isDepthFuncDirty) {
  10096. gl.depthFunc(this.depthFunc);
  10097. this._isDepthFuncDirty = false;
  10098. }
  10099. // zOffset
  10100. if (this._isZOffsetDirty) {
  10101. if (this.zOffset) {
  10102. gl.enable(gl.POLYGON_OFFSET_FILL);
  10103. gl.polygonOffset(this.zOffset, 0);
  10104. }
  10105. else {
  10106. gl.disable(gl.POLYGON_OFFSET_FILL);
  10107. }
  10108. this._isZOffsetDirty = false;
  10109. }
  10110. // Front face
  10111. if (this._isFrontFaceDirty) {
  10112. gl.frontFace(this.frontFace);
  10113. this._isFrontFaceDirty = false;
  10114. }
  10115. };
  10116. return _DepthCullingState;
  10117. }());
  10118. BABYLON._DepthCullingState = _DepthCullingState;
  10119. })(BABYLON || (BABYLON = {}));
  10120. //# sourceMappingURL=babylon.depthCullingState.js.map
  10121. "use strict";
  10122. var BABYLON;
  10123. (function (BABYLON) {
  10124. var _StencilState = /** @class */ (function () {
  10125. function _StencilState() {
  10126. this._isStencilTestDirty = false;
  10127. this._isStencilMaskDirty = false;
  10128. this._isStencilFuncDirty = false;
  10129. this._isStencilOpDirty = false;
  10130. this.reset();
  10131. }
  10132. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10133. get: function () {
  10134. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10135. },
  10136. enumerable: true,
  10137. configurable: true
  10138. });
  10139. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10140. get: function () {
  10141. return this._stencilFunc;
  10142. },
  10143. set: function (value) {
  10144. if (this._stencilFunc === value) {
  10145. return;
  10146. }
  10147. this._stencilFunc = value;
  10148. this._isStencilFuncDirty = true;
  10149. },
  10150. enumerable: true,
  10151. configurable: true
  10152. });
  10153. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10154. get: function () {
  10155. return this._stencilFuncRef;
  10156. },
  10157. set: function (value) {
  10158. if (this._stencilFuncRef === value) {
  10159. return;
  10160. }
  10161. this._stencilFuncRef = value;
  10162. this._isStencilFuncDirty = true;
  10163. },
  10164. enumerable: true,
  10165. configurable: true
  10166. });
  10167. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10168. get: function () {
  10169. return this._stencilFuncMask;
  10170. },
  10171. set: function (value) {
  10172. if (this._stencilFuncMask === value) {
  10173. return;
  10174. }
  10175. this._stencilFuncMask = value;
  10176. this._isStencilFuncDirty = true;
  10177. },
  10178. enumerable: true,
  10179. configurable: true
  10180. });
  10181. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10182. get: function () {
  10183. return this._stencilOpStencilFail;
  10184. },
  10185. set: function (value) {
  10186. if (this._stencilOpStencilFail === value) {
  10187. return;
  10188. }
  10189. this._stencilOpStencilFail = value;
  10190. this._isStencilOpDirty = true;
  10191. },
  10192. enumerable: true,
  10193. configurable: true
  10194. });
  10195. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10196. get: function () {
  10197. return this._stencilOpDepthFail;
  10198. },
  10199. set: function (value) {
  10200. if (this._stencilOpDepthFail === value) {
  10201. return;
  10202. }
  10203. this._stencilOpDepthFail = value;
  10204. this._isStencilOpDirty = true;
  10205. },
  10206. enumerable: true,
  10207. configurable: true
  10208. });
  10209. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10210. get: function () {
  10211. return this._stencilOpStencilDepthPass;
  10212. },
  10213. set: function (value) {
  10214. if (this._stencilOpStencilDepthPass === value) {
  10215. return;
  10216. }
  10217. this._stencilOpStencilDepthPass = value;
  10218. this._isStencilOpDirty = true;
  10219. },
  10220. enumerable: true,
  10221. configurable: true
  10222. });
  10223. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10224. get: function () {
  10225. return this._stencilMask;
  10226. },
  10227. set: function (value) {
  10228. if (this._stencilMask === value) {
  10229. return;
  10230. }
  10231. this._stencilMask = value;
  10232. this._isStencilMaskDirty = true;
  10233. },
  10234. enumerable: true,
  10235. configurable: true
  10236. });
  10237. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10238. get: function () {
  10239. return this._stencilTest;
  10240. },
  10241. set: function (value) {
  10242. if (this._stencilTest === value) {
  10243. return;
  10244. }
  10245. this._stencilTest = value;
  10246. this._isStencilTestDirty = true;
  10247. },
  10248. enumerable: true,
  10249. configurable: true
  10250. });
  10251. _StencilState.prototype.reset = function () {
  10252. this._stencilTest = false;
  10253. this._stencilMask = 0xFF;
  10254. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10255. this._stencilFuncRef = 1;
  10256. this._stencilFuncMask = 0xFF;
  10257. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10258. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10259. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10260. this._isStencilTestDirty = true;
  10261. this._isStencilMaskDirty = true;
  10262. this._isStencilFuncDirty = true;
  10263. this._isStencilOpDirty = true;
  10264. };
  10265. _StencilState.prototype.apply = function (gl) {
  10266. if (!this.isDirty) {
  10267. return;
  10268. }
  10269. // Stencil test
  10270. if (this._isStencilTestDirty) {
  10271. if (this.stencilTest) {
  10272. gl.enable(gl.STENCIL_TEST);
  10273. }
  10274. else {
  10275. gl.disable(gl.STENCIL_TEST);
  10276. }
  10277. this._isStencilTestDirty = false;
  10278. }
  10279. // Stencil mask
  10280. if (this._isStencilMaskDirty) {
  10281. gl.stencilMask(this.stencilMask);
  10282. this._isStencilMaskDirty = false;
  10283. }
  10284. // Stencil func
  10285. if (this._isStencilFuncDirty) {
  10286. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10287. this._isStencilFuncDirty = false;
  10288. }
  10289. // Stencil op
  10290. if (this._isStencilOpDirty) {
  10291. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10292. this._isStencilOpDirty = false;
  10293. }
  10294. };
  10295. return _StencilState;
  10296. }());
  10297. BABYLON._StencilState = _StencilState;
  10298. })(BABYLON || (BABYLON = {}));
  10299. //# sourceMappingURL=babylon.stencilState.js.map
  10300. "use strict";
  10301. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10302. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10303. s = arguments[i];
  10304. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10305. t[p] = s[p];
  10306. }
  10307. return t;
  10308. };
  10309. var BABYLON;
  10310. (function (BABYLON) {
  10311. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10312. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10313. };
  10314. var compileRawShader = function (gl, source, type) {
  10315. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10316. gl.shaderSource(shader, source);
  10317. gl.compileShader(shader);
  10318. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10319. var log = gl.getShaderInfoLog(shader);
  10320. if (log) {
  10321. throw new Error(log);
  10322. }
  10323. }
  10324. if (!shader) {
  10325. throw new Error("Something went wrong while compile the shader.");
  10326. }
  10327. return shader;
  10328. };
  10329. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10330. var magFilter = gl.NEAREST;
  10331. var minFilter = gl.NEAREST;
  10332. switch (samplingMode) {
  10333. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10334. magFilter = gl.LINEAR;
  10335. if (generateMipMaps) {
  10336. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10337. }
  10338. else {
  10339. minFilter = gl.LINEAR;
  10340. }
  10341. break;
  10342. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10343. magFilter = gl.LINEAR;
  10344. if (generateMipMaps) {
  10345. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10346. }
  10347. else {
  10348. minFilter = gl.LINEAR;
  10349. }
  10350. break;
  10351. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10352. magFilter = gl.NEAREST;
  10353. if (generateMipMaps) {
  10354. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10355. }
  10356. else {
  10357. minFilter = gl.NEAREST;
  10358. }
  10359. break;
  10360. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10361. magFilter = gl.NEAREST;
  10362. if (generateMipMaps) {
  10363. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10364. }
  10365. else {
  10366. minFilter = gl.NEAREST;
  10367. }
  10368. break;
  10369. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10370. magFilter = gl.NEAREST;
  10371. if (generateMipMaps) {
  10372. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10373. }
  10374. else {
  10375. minFilter = gl.LINEAR;
  10376. }
  10377. break;
  10378. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10379. magFilter = gl.NEAREST;
  10380. if (generateMipMaps) {
  10381. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10382. }
  10383. else {
  10384. minFilter = gl.LINEAR;
  10385. }
  10386. break;
  10387. case BABYLON.Texture.NEAREST_LINEAR:
  10388. magFilter = gl.NEAREST;
  10389. minFilter = gl.LINEAR;
  10390. break;
  10391. case BABYLON.Texture.NEAREST_NEAREST:
  10392. magFilter = gl.NEAREST;
  10393. minFilter = gl.NEAREST;
  10394. break;
  10395. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10396. magFilter = gl.LINEAR;
  10397. if (generateMipMaps) {
  10398. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10399. }
  10400. else {
  10401. minFilter = gl.NEAREST;
  10402. }
  10403. break;
  10404. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10405. magFilter = gl.LINEAR;
  10406. if (generateMipMaps) {
  10407. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10408. }
  10409. else {
  10410. minFilter = gl.NEAREST;
  10411. }
  10412. break;
  10413. case BABYLON.Texture.LINEAR_LINEAR:
  10414. magFilter = gl.LINEAR;
  10415. minFilter = gl.LINEAR;
  10416. break;
  10417. case BABYLON.Texture.LINEAR_NEAREST:
  10418. magFilter = gl.LINEAR;
  10419. minFilter = gl.NEAREST;
  10420. break;
  10421. }
  10422. return {
  10423. min: minFilter,
  10424. mag: magFilter
  10425. };
  10426. };
  10427. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10428. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10429. var img;
  10430. var onload = function () {
  10431. loadedImages[index] = img;
  10432. loadedImages._internalCount++;
  10433. if (scene) {
  10434. scene._removePendingData(img);
  10435. }
  10436. if (loadedImages._internalCount === 6) {
  10437. onfinish(loadedImages);
  10438. }
  10439. };
  10440. var onerror = function (message, exception) {
  10441. if (scene) {
  10442. scene._removePendingData(img);
  10443. }
  10444. if (onErrorCallBack) {
  10445. onErrorCallBack(message, exception);
  10446. }
  10447. };
  10448. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10449. if (scene) {
  10450. scene._addPendingData(img);
  10451. }
  10452. };
  10453. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10454. if (onError === void 0) { onError = null; }
  10455. var loadedImages = [];
  10456. loadedImages._internalCount = 0;
  10457. for (var index = 0; index < 6; index++) {
  10458. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10459. }
  10460. };
  10461. var BufferPointer = /** @class */ (function () {
  10462. function BufferPointer() {
  10463. }
  10464. return BufferPointer;
  10465. }());
  10466. var InstancingAttributeInfo = /** @class */ (function () {
  10467. function InstancingAttributeInfo() {
  10468. }
  10469. return InstancingAttributeInfo;
  10470. }());
  10471. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10472. /**
  10473. * Define options used to create a render target texture
  10474. */
  10475. var RenderTargetCreationOptions = /** @class */ (function () {
  10476. function RenderTargetCreationOptions() {
  10477. }
  10478. return RenderTargetCreationOptions;
  10479. }());
  10480. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10481. /**
  10482. * Define options used to create a depth texture
  10483. */
  10484. var DepthTextureCreationOptions = /** @class */ (function () {
  10485. function DepthTextureCreationOptions() {
  10486. }
  10487. return DepthTextureCreationOptions;
  10488. }());
  10489. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10490. /**
  10491. * Regroup several parameters relative to the browser in use
  10492. */
  10493. var EngineCapabilities = /** @class */ (function () {
  10494. function EngineCapabilities() {
  10495. }
  10496. return EngineCapabilities;
  10497. }());
  10498. BABYLON.EngineCapabilities = EngineCapabilities;
  10499. /**
  10500. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10501. */
  10502. var Engine = /** @class */ (function () {
  10503. /**
  10504. * @constructor
  10505. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10506. * @param antialias defines enable antialiasing (default: false)
  10507. * @param options defines further options to be sent to the getContext() function
  10508. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10509. */
  10510. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10511. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10512. var _this = this;
  10513. // Public members
  10514. this.forcePOTTextures = false;
  10515. this.isFullscreen = false;
  10516. this.isPointerLock = false;
  10517. this.cullBackFaces = true;
  10518. this.renderEvenInBackground = true;
  10519. this.preventCacheWipeBetweenFrames = false;
  10520. // To enable/disable IDB support and avoid XHR on .manifest
  10521. this.enableOfflineSupport = false;
  10522. this.scenes = new Array();
  10523. this.postProcesses = new Array();
  10524. // Observables
  10525. /**
  10526. * Observable event triggered each time the rendering canvas is resized
  10527. */
  10528. this.onResizeObservable = new BABYLON.Observable();
  10529. /**
  10530. * Observable event triggered each time the canvas loses focus
  10531. */
  10532. this.onCanvasBlurObservable = new BABYLON.Observable();
  10533. /**
  10534. * Observable event triggered each time the canvas gains focus
  10535. */
  10536. this.onCanvasFocusObservable = new BABYLON.Observable();
  10537. /**
  10538. * Observable event triggered each time the canvas receives pointerout event
  10539. */
  10540. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10541. /**
  10542. * Observable event triggered before each texture is initialized
  10543. */
  10544. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10545. //WebVR
  10546. this._vrDisplay = undefined;
  10547. this._vrSupported = false;
  10548. this._vrExclusivePointerMode = false;
  10549. // Uniform buffers list
  10550. this.disableUniformBuffers = false;
  10551. this._uniformBuffers = new Array();
  10552. // Observables
  10553. /**
  10554. * Observable raised when the engine begins a new frame
  10555. */
  10556. this.onBeginFrameObservable = new BABYLON.Observable();
  10557. /**
  10558. * Observable raised when the engine ends the current frame
  10559. */
  10560. this.onEndFrameObservable = new BABYLON.Observable();
  10561. /**
  10562. * Observable raised when the engine is about to compile a shader
  10563. */
  10564. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10565. /**
  10566. * Observable raised when the engine has jsut compiled a shader
  10567. */
  10568. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10569. this._windowIsBackground = false;
  10570. this._webGLVersion = 1.0;
  10571. this._badOS = false;
  10572. this._badDesktopOS = false;
  10573. /**
  10574. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10575. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10576. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10577. */
  10578. this.disableTextureBindingOptimization = false;
  10579. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10580. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10581. this.onVRRequestPresentStart = new BABYLON.Observable();
  10582. this._colorWrite = true;
  10583. this._drawCalls = new BABYLON.PerfCounter();
  10584. this._textureCollisions = new BABYLON.PerfCounter();
  10585. this._renderingQueueLaunched = false;
  10586. this._activeRenderLoops = new Array();
  10587. // Deterministic lockstepMaxSteps
  10588. this._deterministicLockstep = false;
  10589. this._lockstepMaxSteps = 4;
  10590. // Lost context
  10591. this.onContextLostObservable = new BABYLON.Observable();
  10592. this.onContextRestoredObservable = new BABYLON.Observable();
  10593. this._contextWasLost = false;
  10594. this._doNotHandleContextLost = false;
  10595. // FPS
  10596. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10597. this._fps = 60;
  10598. this._deltaTime = 0;
  10599. /**
  10600. * Turn this value on if you want to pause FPS computation when in background
  10601. */
  10602. this.disablePerformanceMonitorInBackground = false;
  10603. // States
  10604. this._depthCullingState = new BABYLON._DepthCullingState();
  10605. this._stencilState = new BABYLON._StencilState();
  10606. this._alphaState = new BABYLON._AlphaState();
  10607. this._alphaMode = Engine.ALPHA_DISABLE;
  10608. // Cache
  10609. this._internalTexturesCache = new Array();
  10610. this._activeChannel = 0;
  10611. this._currentTextureChannel = -1;
  10612. this._boundTexturesCache = {};
  10613. this._compiledEffects = {};
  10614. this._vertexAttribArraysEnabled = [];
  10615. this._uintIndicesCurrentlySet = false;
  10616. this._currentBoundBuffer = new Array();
  10617. this._currentBufferPointers = new Array();
  10618. this._currentInstanceLocations = new Array();
  10619. this._currentInstanceBuffers = new Array();
  10620. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10621. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10622. this._vaoRecordInProgress = false;
  10623. this._mustWipeVertexAttributes = false;
  10624. this._nextFreeTextureSlots = new Array();
  10625. this._maxSimultaneousTextures = 0;
  10626. this._activeRequests = new Array();
  10627. // Hardware supported Compressed Textures
  10628. this._texturesSupported = new Array();
  10629. this._onVRFullScreenTriggered = function () {
  10630. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10631. //get the old size before we change
  10632. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10633. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10634. //get the width and height, change the render size
  10635. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10636. _this.setHardwareScalingLevel(1);
  10637. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10638. }
  10639. else {
  10640. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10641. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10642. }
  10643. };
  10644. this._boundUniforms = {};
  10645. // Register promises
  10646. BABYLON.PromisePolyfill.Apply();
  10647. var canvas = null;
  10648. Engine.Instances.push(this);
  10649. if (!canvasOrContext) {
  10650. return;
  10651. }
  10652. options = options || {};
  10653. if (canvasOrContext.getContext) {
  10654. canvas = canvasOrContext;
  10655. this._renderingCanvas = canvas;
  10656. if (antialias != null) {
  10657. options.antialias = antialias;
  10658. }
  10659. if (options.deterministicLockstep === undefined) {
  10660. options.deterministicLockstep = false;
  10661. }
  10662. if (options.lockstepMaxSteps === undefined) {
  10663. options.lockstepMaxSteps = 4;
  10664. }
  10665. if (options.preserveDrawingBuffer === undefined) {
  10666. options.preserveDrawingBuffer = false;
  10667. }
  10668. if (options.audioEngine === undefined) {
  10669. options.audioEngine = true;
  10670. }
  10671. if (options.stencil === undefined) {
  10672. options.stencil = true;
  10673. }
  10674. this._deterministicLockstep = options.deterministicLockstep;
  10675. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10676. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10677. // Exceptions
  10678. if (navigator && navigator.userAgent) {
  10679. var ua = navigator.userAgent;
  10680. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10681. var exception = _a[_i];
  10682. var key = exception.key;
  10683. var targets = exception.targets;
  10684. if (ua.indexOf(key) > -1) {
  10685. if (exception.capture && exception.captureConstraint) {
  10686. var capture = exception.capture;
  10687. var constraint = exception.captureConstraint;
  10688. var regex = new RegExp(capture);
  10689. var matches = regex.exec(ua);
  10690. if (matches && matches.length > 0) {
  10691. var capturedValue = parseInt(matches[matches.length - 1]);
  10692. if (capturedValue >= constraint) {
  10693. continue;
  10694. }
  10695. }
  10696. }
  10697. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10698. var target = targets_1[_b];
  10699. switch (target) {
  10700. case "uniformBuffer":
  10701. this.disableUniformBuffers = true;
  10702. break;
  10703. case "textureBindingOptimization":
  10704. this.disableTextureBindingOptimization = true;
  10705. break;
  10706. }
  10707. }
  10708. }
  10709. }
  10710. }
  10711. // GL
  10712. if (!options.disableWebGL2Support) {
  10713. try {
  10714. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10715. if (this._gl) {
  10716. this._webGLVersion = 2.0;
  10717. }
  10718. }
  10719. catch (e) {
  10720. // Do nothing
  10721. }
  10722. }
  10723. if (!this._gl) {
  10724. if (!canvas) {
  10725. throw new Error("The provided canvas is null or undefined.");
  10726. }
  10727. try {
  10728. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10729. }
  10730. catch (e) {
  10731. throw new Error("WebGL not supported");
  10732. }
  10733. }
  10734. if (!this._gl) {
  10735. throw new Error("WebGL not supported");
  10736. }
  10737. this._onCanvasFocus = function () {
  10738. _this.onCanvasFocusObservable.notifyObservers(_this);
  10739. };
  10740. this._onCanvasBlur = function () {
  10741. _this.onCanvasBlurObservable.notifyObservers(_this);
  10742. };
  10743. canvas.addEventListener("focus", this._onCanvasFocus);
  10744. canvas.addEventListener("blur", this._onCanvasBlur);
  10745. this._onBlur = function () {
  10746. if (_this.disablePerformanceMonitorInBackground) {
  10747. _this._performanceMonitor.disable();
  10748. }
  10749. _this._windowIsBackground = true;
  10750. };
  10751. this._onFocus = function () {
  10752. if (_this.disablePerformanceMonitorInBackground) {
  10753. _this._performanceMonitor.enable();
  10754. }
  10755. _this._windowIsBackground = false;
  10756. };
  10757. this._onCanvasPointerOut = function (ev) {
  10758. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10759. };
  10760. window.addEventListener("blur", this._onBlur);
  10761. window.addEventListener("focus", this._onFocus);
  10762. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10763. // Context lost
  10764. if (!this._doNotHandleContextLost) {
  10765. this._onContextLost = function (evt) {
  10766. evt.preventDefault();
  10767. _this._contextWasLost = true;
  10768. BABYLON.Tools.Warn("WebGL context lost.");
  10769. _this.onContextLostObservable.notifyObservers(_this);
  10770. };
  10771. this._onContextRestored = function (evt) {
  10772. // Adding a timeout to avoid race condition at browser level
  10773. setTimeout(function () {
  10774. // Rebuild gl context
  10775. _this._initGLContext();
  10776. // Rebuild effects
  10777. _this._rebuildEffects();
  10778. // Rebuild textures
  10779. _this._rebuildInternalTextures();
  10780. // Rebuild buffers
  10781. _this._rebuildBuffers();
  10782. // Cache
  10783. _this.wipeCaches(true);
  10784. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10785. _this.onContextRestoredObservable.notifyObservers(_this);
  10786. _this._contextWasLost = false;
  10787. }, 0);
  10788. };
  10789. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10790. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10791. }
  10792. }
  10793. else {
  10794. this._gl = canvasOrContext;
  10795. this._renderingCanvas = this._gl.canvas;
  10796. if (this._gl.renderbufferStorageMultisample) {
  10797. this._webGLVersion = 2.0;
  10798. }
  10799. options.stencil = this._gl.getContextAttributes().stencil;
  10800. }
  10801. // Viewport
  10802. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10803. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10804. this.resize();
  10805. this._isStencilEnable = options.stencil ? true : false;
  10806. this._initGLContext();
  10807. if (canvas) {
  10808. // Fullscreen
  10809. this._onFullscreenChange = function () {
  10810. if (document.fullscreen !== undefined) {
  10811. _this.isFullscreen = document.fullscreen;
  10812. }
  10813. else if (document.mozFullScreen !== undefined) {
  10814. _this.isFullscreen = document.mozFullScreen;
  10815. }
  10816. else if (document.webkitIsFullScreen !== undefined) {
  10817. _this.isFullscreen = document.webkitIsFullScreen;
  10818. }
  10819. else if (document.msIsFullScreen !== undefined) {
  10820. _this.isFullscreen = document.msIsFullScreen;
  10821. }
  10822. // Pointer lock
  10823. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10824. canvas.requestPointerLock = canvas.requestPointerLock ||
  10825. canvas.msRequestPointerLock ||
  10826. canvas.mozRequestPointerLock ||
  10827. canvas.webkitRequestPointerLock;
  10828. if (canvas.requestPointerLock) {
  10829. canvas.requestPointerLock();
  10830. }
  10831. }
  10832. };
  10833. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10834. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10835. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10836. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10837. // Pointer lock
  10838. this._onPointerLockChange = function () {
  10839. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10840. document.webkitPointerLockElement === canvas ||
  10841. document.msPointerLockElement === canvas ||
  10842. document.pointerLockElement === canvas);
  10843. };
  10844. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10845. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10846. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10847. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10848. this._onVRDisplayPointerRestricted = function () {
  10849. if (canvas) {
  10850. canvas.requestPointerLock();
  10851. }
  10852. };
  10853. this._onVRDisplayPointerUnrestricted = function () {
  10854. document.exitPointerLock();
  10855. };
  10856. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10857. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10858. }
  10859. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10860. Engine.audioEngine = new BABYLON.AudioEngine();
  10861. }
  10862. // Prepare buffer pointers
  10863. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10864. this._currentBufferPointers[i] = new BufferPointer();
  10865. }
  10866. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10867. // Load WebVR Devices
  10868. if (options.autoEnableWebVR) {
  10869. this.initWebVR();
  10870. }
  10871. // Detect if we are running on a faulty buggy OS.
  10872. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10873. // Detect if we are running on a faulty buggy desktop OS.
  10874. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10875. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10876. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10877. }
  10878. Object.defineProperty(Engine, "LastCreatedEngine", {
  10879. get: function () {
  10880. if (Engine.Instances.length === 0) {
  10881. return null;
  10882. }
  10883. return Engine.Instances[Engine.Instances.length - 1];
  10884. },
  10885. enumerable: true,
  10886. configurable: true
  10887. });
  10888. Object.defineProperty(Engine, "LastCreatedScene", {
  10889. get: function () {
  10890. var lastCreatedEngine = Engine.LastCreatedEngine;
  10891. if (!lastCreatedEngine) {
  10892. return null;
  10893. }
  10894. if (lastCreatedEngine.scenes.length === 0) {
  10895. return null;
  10896. }
  10897. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10898. },
  10899. enumerable: true,
  10900. configurable: true
  10901. });
  10902. /**
  10903. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10904. */
  10905. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10906. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10907. var engine = Engine.Instances[engineIndex];
  10908. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10909. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10910. }
  10911. }
  10912. };
  10913. Object.defineProperty(Engine, "NEVER", {
  10914. get: function () {
  10915. return Engine._NEVER;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(Engine, "ALWAYS", {
  10921. get: function () {
  10922. return Engine._ALWAYS;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(Engine, "LESS", {
  10928. get: function () {
  10929. return Engine._LESS;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(Engine, "EQUAL", {
  10935. get: function () {
  10936. return Engine._EQUAL;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(Engine, "LEQUAL", {
  10942. get: function () {
  10943. return Engine._LEQUAL;
  10944. },
  10945. enumerable: true,
  10946. configurable: true
  10947. });
  10948. Object.defineProperty(Engine, "GREATER", {
  10949. get: function () {
  10950. return Engine._GREATER;
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. Object.defineProperty(Engine, "GEQUAL", {
  10956. get: function () {
  10957. return Engine._GEQUAL;
  10958. },
  10959. enumerable: true,
  10960. configurable: true
  10961. });
  10962. Object.defineProperty(Engine, "NOTEQUAL", {
  10963. get: function () {
  10964. return Engine._NOTEQUAL;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. Object.defineProperty(Engine, "KEEP", {
  10970. get: function () {
  10971. return Engine._KEEP;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Object.defineProperty(Engine, "REPLACE", {
  10977. get: function () {
  10978. return Engine._REPLACE;
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(Engine, "INCR", {
  10984. get: function () {
  10985. return Engine._INCR;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(Engine, "DECR", {
  10991. get: function () {
  10992. return Engine._DECR;
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(Engine, "INVERT", {
  10998. get: function () {
  10999. return Engine._INVERT;
  11000. },
  11001. enumerable: true,
  11002. configurable: true
  11003. });
  11004. Object.defineProperty(Engine, "INCR_WRAP", {
  11005. get: function () {
  11006. return Engine._INCR_WRAP;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(Engine, "DECR_WRAP", {
  11012. get: function () {
  11013. return Engine._DECR_WRAP;
  11014. },
  11015. enumerable: true,
  11016. configurable: true
  11017. });
  11018. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11019. get: function () {
  11020. return Engine._ALPHA_DISABLE;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11026. get: function () {
  11027. return Engine._ALPHA_ONEONE;
  11028. },
  11029. enumerable: true,
  11030. configurable: true
  11031. });
  11032. Object.defineProperty(Engine, "ALPHA_ADD", {
  11033. get: function () {
  11034. return Engine._ALPHA_ADD;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11040. get: function () {
  11041. return Engine._ALPHA_COMBINE;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11047. get: function () {
  11048. return Engine._ALPHA_SUBTRACT;
  11049. },
  11050. enumerable: true,
  11051. configurable: true
  11052. });
  11053. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11054. get: function () {
  11055. return Engine._ALPHA_MULTIPLY;
  11056. },
  11057. enumerable: true,
  11058. configurable: true
  11059. });
  11060. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11061. get: function () {
  11062. return Engine._ALPHA_MAXIMIZED;
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11068. get: function () {
  11069. return Engine._ALPHA_PREMULTIPLIED;
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11075. get: function () {
  11076. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11077. },
  11078. enumerable: true,
  11079. configurable: true
  11080. });
  11081. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11082. get: function () {
  11083. return Engine._ALPHA_INTERPOLATE;
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11089. get: function () {
  11090. return Engine._ALPHA_SCREENMODE;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11096. get: function () {
  11097. return Engine._DELAYLOADSTATE_NONE;
  11098. },
  11099. enumerable: true,
  11100. configurable: true
  11101. });
  11102. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11103. get: function () {
  11104. return Engine._DELAYLOADSTATE_LOADED;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11110. get: function () {
  11111. return Engine._DELAYLOADSTATE_LOADING;
  11112. },
  11113. enumerable: true,
  11114. configurable: true
  11115. });
  11116. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11117. get: function () {
  11118. return Engine._DELAYLOADSTATE_NOTLOADED;
  11119. },
  11120. enumerable: true,
  11121. configurable: true
  11122. });
  11123. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11124. get: function () {
  11125. return Engine._TEXTUREFORMAT_ALPHA;
  11126. },
  11127. enumerable: true,
  11128. configurable: true
  11129. });
  11130. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11131. get: function () {
  11132. return Engine._TEXTUREFORMAT_LUMINANCE;
  11133. },
  11134. enumerable: true,
  11135. configurable: true
  11136. });
  11137. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11138. /**
  11139. * R32F
  11140. */
  11141. get: function () {
  11142. return Engine._TEXTUREFORMAT_R32F;
  11143. },
  11144. enumerable: true,
  11145. configurable: true
  11146. });
  11147. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11148. /**
  11149. * RG32F
  11150. */
  11151. get: function () {
  11152. return Engine._TEXTUREFORMAT_RG32F;
  11153. },
  11154. enumerable: true,
  11155. configurable: true
  11156. });
  11157. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11158. /**
  11159. * RGB32F
  11160. */
  11161. get: function () {
  11162. return Engine._TEXTUREFORMAT_RGB32F;
  11163. },
  11164. enumerable: true,
  11165. configurable: true
  11166. });
  11167. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11168. /**
  11169. * RGBA32F
  11170. */
  11171. get: function () {
  11172. return Engine._TEXTUREFORMAT_RGBA32F;
  11173. },
  11174. enumerable: true,
  11175. configurable: true
  11176. });
  11177. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11178. get: function () {
  11179. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11180. },
  11181. enumerable: true,
  11182. configurable: true
  11183. });
  11184. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11185. get: function () {
  11186. return Engine._TEXTUREFORMAT_RGB;
  11187. },
  11188. enumerable: true,
  11189. configurable: true
  11190. });
  11191. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11192. get: function () {
  11193. return Engine._TEXTUREFORMAT_RGBA;
  11194. },
  11195. enumerable: true,
  11196. configurable: true
  11197. });
  11198. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11199. get: function () {
  11200. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11201. },
  11202. enumerable: true,
  11203. configurable: true
  11204. });
  11205. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11206. get: function () {
  11207. return Engine._TEXTURETYPE_FLOAT;
  11208. },
  11209. enumerable: true,
  11210. configurable: true
  11211. });
  11212. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11213. get: function () {
  11214. return Engine._TEXTURETYPE_HALF_FLOAT;
  11215. },
  11216. enumerable: true,
  11217. configurable: true
  11218. });
  11219. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11220. get: function () {
  11221. return Engine._SCALEMODE_FLOOR;
  11222. },
  11223. enumerable: true,
  11224. configurable: true
  11225. });
  11226. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11227. get: function () {
  11228. return Engine._SCALEMODE_NEAREST;
  11229. },
  11230. enumerable: true,
  11231. configurable: true
  11232. });
  11233. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11234. get: function () {
  11235. return Engine._SCALEMODE_CEILING;
  11236. },
  11237. enumerable: true,
  11238. configurable: true
  11239. });
  11240. Object.defineProperty(Engine, "Version", {
  11241. get: function () {
  11242. return "3.2.0-beta.1";
  11243. },
  11244. enumerable: true,
  11245. configurable: true
  11246. });
  11247. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11248. get: function () {
  11249. return this._vrExclusivePointerMode;
  11250. },
  11251. enumerable: true,
  11252. configurable: true
  11253. });
  11254. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11255. get: function () {
  11256. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11257. },
  11258. enumerable: true,
  11259. configurable: true
  11260. });
  11261. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11262. get: function () {
  11263. return this._webGLVersion < 2 || this.forcePOTTextures;
  11264. },
  11265. enumerable: true,
  11266. configurable: true
  11267. });
  11268. Object.defineProperty(Engine.prototype, "badOS", {
  11269. get: function () {
  11270. return this._badOS;
  11271. },
  11272. enumerable: true,
  11273. configurable: true
  11274. });
  11275. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11276. get: function () {
  11277. return this._badDesktopOS;
  11278. },
  11279. enumerable: true,
  11280. configurable: true
  11281. });
  11282. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11283. get: function () {
  11284. return this._performanceMonitor;
  11285. },
  11286. enumerable: true,
  11287. configurable: true
  11288. });
  11289. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11290. get: function () {
  11291. return this._texturesSupported;
  11292. },
  11293. enumerable: true,
  11294. configurable: true
  11295. });
  11296. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11297. get: function () {
  11298. return this._textureFormatInUse;
  11299. },
  11300. enumerable: true,
  11301. configurable: true
  11302. });
  11303. Object.defineProperty(Engine.prototype, "currentViewport", {
  11304. get: function () {
  11305. return this._cachedViewport;
  11306. },
  11307. enumerable: true,
  11308. configurable: true
  11309. });
  11310. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11311. // Empty texture
  11312. get: function () {
  11313. if (!this._emptyTexture) {
  11314. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11315. }
  11316. return this._emptyTexture;
  11317. },
  11318. enumerable: true,
  11319. configurable: true
  11320. });
  11321. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11322. get: function () {
  11323. if (!this._emptyTexture3D) {
  11324. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11325. }
  11326. return this._emptyTexture3D;
  11327. },
  11328. enumerable: true,
  11329. configurable: true
  11330. });
  11331. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11332. get: function () {
  11333. if (!this._emptyCubeTexture) {
  11334. var faceData = new Uint8Array(4);
  11335. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11336. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11337. }
  11338. return this._emptyCubeTexture;
  11339. },
  11340. enumerable: true,
  11341. configurable: true
  11342. });
  11343. Engine.prototype._rebuildInternalTextures = function () {
  11344. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11345. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11346. var internalTexture = currentState_1[_i];
  11347. internalTexture._rebuild();
  11348. }
  11349. };
  11350. Engine.prototype._rebuildEffects = function () {
  11351. for (var key in this._compiledEffects) {
  11352. var effect = this._compiledEffects[key];
  11353. effect._prepareEffect();
  11354. }
  11355. BABYLON.Effect.ResetCache();
  11356. };
  11357. Engine.prototype._rebuildBuffers = function () {
  11358. // Index / Vertex
  11359. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11360. var scene = _a[_i];
  11361. scene.resetCachedMaterial();
  11362. scene._rebuildGeometries();
  11363. scene._rebuildTextures();
  11364. }
  11365. // Uniforms
  11366. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11367. var uniformBuffer = _c[_b];
  11368. uniformBuffer._rebuild();
  11369. }
  11370. };
  11371. Engine.prototype._initGLContext = function () {
  11372. // Caps
  11373. this._caps = new EngineCapabilities();
  11374. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11375. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11376. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11377. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11378. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11379. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11380. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11381. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11382. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11383. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11384. // Infos
  11385. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11386. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11387. if (rendererInfo != null) {
  11388. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11389. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11390. }
  11391. if (!this._glVendor) {
  11392. this._glVendor = "Unknown vendor";
  11393. }
  11394. if (!this._glRenderer) {
  11395. this._glRenderer = "Unknown renderer";
  11396. }
  11397. // Constants
  11398. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11399. if (this._gl.RGBA16F !== 0x881A) {
  11400. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11401. }
  11402. if (this._gl.RGBA32F !== 0x8814) {
  11403. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11404. }
  11405. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11406. this._gl.DEPTH24_STENCIL8 = 35056;
  11407. }
  11408. // Extensions
  11409. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11410. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11411. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11412. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11413. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11414. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11415. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11416. 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');
  11417. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11418. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11419. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11420. this._caps.highPrecisionShaderSupported = true;
  11421. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11422. if (this._caps.timerQuery) {
  11423. if (this._webGLVersion === 1) {
  11424. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11425. }
  11426. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11427. }
  11428. // Checks if some of the format renders first to allow the use of webgl inspector.
  11429. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11430. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11431. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11432. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11433. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11434. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11435. if (this._webGLVersion > 1) {
  11436. this._gl.HALF_FLOAT_OES = 0x140B;
  11437. }
  11438. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11439. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11440. // Draw buffers
  11441. if (this._webGLVersion > 1) {
  11442. this._caps.drawBuffersExtension = true;
  11443. }
  11444. else {
  11445. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11446. if (drawBuffersExtension !== null) {
  11447. this._caps.drawBuffersExtension = true;
  11448. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11449. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11450. for (var i = 0; i < 16; i++) {
  11451. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11452. }
  11453. }
  11454. else {
  11455. this._caps.drawBuffersExtension = false;
  11456. }
  11457. }
  11458. // Depth Texture
  11459. if (this._webGLVersion > 1) {
  11460. this._caps.depthTextureExtension = true;
  11461. }
  11462. else {
  11463. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11464. if (depthTextureExtension != null) {
  11465. this._caps.depthTextureExtension = true;
  11466. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11467. }
  11468. }
  11469. // Vertex array object
  11470. if (this._webGLVersion > 1) {
  11471. this._caps.vertexArrayObject = true;
  11472. }
  11473. else {
  11474. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11475. if (vertexArrayObjectExtension != null) {
  11476. this._caps.vertexArrayObject = true;
  11477. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11478. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11479. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11480. }
  11481. else {
  11482. this._caps.vertexArrayObject = false;
  11483. }
  11484. }
  11485. // Instances count
  11486. if (this._webGLVersion > 1) {
  11487. this._caps.instancedArrays = true;
  11488. }
  11489. else {
  11490. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11491. if (instanceExtension != null) {
  11492. this._caps.instancedArrays = true;
  11493. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11494. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11495. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11496. }
  11497. else {
  11498. this._caps.instancedArrays = false;
  11499. }
  11500. }
  11501. // Intelligently add supported compressed formats in order to check for.
  11502. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11503. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11504. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11505. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11506. if (this._caps.astc)
  11507. this.texturesSupported.push('-astc.ktx');
  11508. if (this._caps.s3tc)
  11509. this.texturesSupported.push('-dxt.ktx');
  11510. if (this._caps.pvrtc)
  11511. this.texturesSupported.push('-pvrtc.ktx');
  11512. if (this._caps.etc2)
  11513. this.texturesSupported.push('-etc2.ktx');
  11514. if (this._caps.etc1)
  11515. this.texturesSupported.push('-etc1.ktx');
  11516. if (this._gl.getShaderPrecisionFormat) {
  11517. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11518. if (highp) {
  11519. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11520. }
  11521. }
  11522. // Depth buffer
  11523. this.setDepthBuffer(true);
  11524. this.setDepthFunctionToLessOrEqual();
  11525. this.setDepthWrite(true);
  11526. // Texture maps
  11527. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11528. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11529. this._nextFreeTextureSlots.push(slot);
  11530. }
  11531. };
  11532. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11533. get: function () {
  11534. return this._webGLVersion;
  11535. },
  11536. enumerable: true,
  11537. configurable: true
  11538. });
  11539. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11540. /**
  11541. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11542. */
  11543. get: function () {
  11544. return this._isStencilEnable;
  11545. },
  11546. enumerable: true,
  11547. configurable: true
  11548. });
  11549. Engine.prototype._prepareWorkingCanvas = function () {
  11550. if (this._workingCanvas) {
  11551. return;
  11552. }
  11553. this._workingCanvas = document.createElement("canvas");
  11554. var context = this._workingCanvas.getContext("2d");
  11555. if (context) {
  11556. this._workingContext = context;
  11557. }
  11558. };
  11559. Engine.prototype.resetTextureCache = function () {
  11560. for (var key in this._boundTexturesCache) {
  11561. var boundTexture = this._boundTexturesCache[key];
  11562. if (boundTexture) {
  11563. this._removeDesignatedSlot(boundTexture);
  11564. }
  11565. this._boundTexturesCache[key] = null;
  11566. }
  11567. if (!this.disableTextureBindingOptimization) {
  11568. this._nextFreeTextureSlots = [];
  11569. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11570. this._nextFreeTextureSlots.push(slot);
  11571. }
  11572. }
  11573. this._currentTextureChannel = -1;
  11574. };
  11575. Engine.prototype.isDeterministicLockStep = function () {
  11576. return this._deterministicLockstep;
  11577. };
  11578. Engine.prototype.getLockstepMaxSteps = function () {
  11579. return this._lockstepMaxSteps;
  11580. };
  11581. Engine.prototype.getGlInfo = function () {
  11582. return {
  11583. vendor: this._glVendor,
  11584. renderer: this._glRenderer,
  11585. version: this._glVersion
  11586. };
  11587. };
  11588. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11589. if (useScreen === void 0) { useScreen = false; }
  11590. var viewport = camera.viewport;
  11591. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11592. };
  11593. Engine.prototype.getRenderWidth = function (useScreen) {
  11594. if (useScreen === void 0) { useScreen = false; }
  11595. if (!useScreen && this._currentRenderTarget) {
  11596. return this._currentRenderTarget.width;
  11597. }
  11598. return this._gl.drawingBufferWidth;
  11599. };
  11600. Engine.prototype.getRenderHeight = function (useScreen) {
  11601. if (useScreen === void 0) { useScreen = false; }
  11602. if (!useScreen && this._currentRenderTarget) {
  11603. return this._currentRenderTarget.height;
  11604. }
  11605. return this._gl.drawingBufferHeight;
  11606. };
  11607. Engine.prototype.getRenderingCanvas = function () {
  11608. return this._renderingCanvas;
  11609. };
  11610. Engine.prototype.getRenderingCanvasClientRect = function () {
  11611. if (!this._renderingCanvas) {
  11612. return null;
  11613. }
  11614. return this._renderingCanvas.getBoundingClientRect();
  11615. };
  11616. Engine.prototype.setHardwareScalingLevel = function (level) {
  11617. this._hardwareScalingLevel = level;
  11618. this.resize();
  11619. };
  11620. Engine.prototype.getHardwareScalingLevel = function () {
  11621. return this._hardwareScalingLevel;
  11622. };
  11623. Engine.prototype.getLoadedTexturesCache = function () {
  11624. return this._internalTexturesCache;
  11625. };
  11626. Engine.prototype.getCaps = function () {
  11627. return this._caps;
  11628. };
  11629. Object.defineProperty(Engine.prototype, "drawCalls", {
  11630. /** The number of draw calls submitted last frame */
  11631. get: function () {
  11632. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11633. return 0;
  11634. },
  11635. enumerable: true,
  11636. configurable: true
  11637. });
  11638. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11639. get: function () {
  11640. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11641. return null;
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. Engine.prototype.getDepthFunction = function () {
  11647. return this._depthCullingState.depthFunc;
  11648. };
  11649. Engine.prototype.setDepthFunction = function (depthFunc) {
  11650. this._depthCullingState.depthFunc = depthFunc;
  11651. };
  11652. Engine.prototype.setDepthFunctionToGreater = function () {
  11653. this._depthCullingState.depthFunc = this._gl.GREATER;
  11654. };
  11655. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11656. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11657. };
  11658. Engine.prototype.setDepthFunctionToLess = function () {
  11659. this._depthCullingState.depthFunc = this._gl.LESS;
  11660. };
  11661. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11662. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11663. };
  11664. Engine.prototype.getStencilBuffer = function () {
  11665. return this._stencilState.stencilTest;
  11666. };
  11667. Engine.prototype.setStencilBuffer = function (enable) {
  11668. this._stencilState.stencilTest = enable;
  11669. };
  11670. Engine.prototype.getStencilMask = function () {
  11671. return this._stencilState.stencilMask;
  11672. };
  11673. Engine.prototype.setStencilMask = function (mask) {
  11674. this._stencilState.stencilMask = mask;
  11675. };
  11676. Engine.prototype.getStencilFunction = function () {
  11677. return this._stencilState.stencilFunc;
  11678. };
  11679. Engine.prototype.getStencilFunctionReference = function () {
  11680. return this._stencilState.stencilFuncRef;
  11681. };
  11682. Engine.prototype.getStencilFunctionMask = function () {
  11683. return this._stencilState.stencilFuncMask;
  11684. };
  11685. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11686. this._stencilState.stencilFunc = stencilFunc;
  11687. };
  11688. Engine.prototype.setStencilFunctionReference = function (reference) {
  11689. this._stencilState.stencilFuncRef = reference;
  11690. };
  11691. Engine.prototype.setStencilFunctionMask = function (mask) {
  11692. this._stencilState.stencilFuncMask = mask;
  11693. };
  11694. Engine.prototype.getStencilOperationFail = function () {
  11695. return this._stencilState.stencilOpStencilFail;
  11696. };
  11697. Engine.prototype.getStencilOperationDepthFail = function () {
  11698. return this._stencilState.stencilOpDepthFail;
  11699. };
  11700. Engine.prototype.getStencilOperationPass = function () {
  11701. return this._stencilState.stencilOpStencilDepthPass;
  11702. };
  11703. Engine.prototype.setStencilOperationFail = function (operation) {
  11704. this._stencilState.stencilOpStencilFail = operation;
  11705. };
  11706. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11707. this._stencilState.stencilOpDepthFail = operation;
  11708. };
  11709. Engine.prototype.setStencilOperationPass = function (operation) {
  11710. this._stencilState.stencilOpStencilDepthPass = operation;
  11711. };
  11712. Engine.prototype.setDitheringState = function (value) {
  11713. if (value) {
  11714. this._gl.enable(this._gl.DITHER);
  11715. }
  11716. else {
  11717. this._gl.disable(this._gl.DITHER);
  11718. }
  11719. };
  11720. Engine.prototype.setRasterizerState = function (value) {
  11721. if (value) {
  11722. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11723. }
  11724. else {
  11725. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11726. }
  11727. };
  11728. /**
  11729. * stop executing a render loop function and remove it from the execution array
  11730. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11731. */
  11732. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11733. if (!renderFunction) {
  11734. this._activeRenderLoops = [];
  11735. return;
  11736. }
  11737. var index = this._activeRenderLoops.indexOf(renderFunction);
  11738. if (index >= 0) {
  11739. this._activeRenderLoops.splice(index, 1);
  11740. }
  11741. };
  11742. Engine.prototype._renderLoop = function () {
  11743. if (!this._contextWasLost) {
  11744. var shouldRender = true;
  11745. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11746. shouldRender = false;
  11747. }
  11748. if (shouldRender) {
  11749. // Start new frame
  11750. this.beginFrame();
  11751. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11752. var renderFunction = this._activeRenderLoops[index];
  11753. renderFunction();
  11754. }
  11755. // Present
  11756. this.endFrame();
  11757. }
  11758. }
  11759. if (this._activeRenderLoops.length > 0) {
  11760. // Register new frame
  11761. var requester = null;
  11762. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11763. requester = this._vrDisplay;
  11764. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11765. }
  11766. else {
  11767. this._renderingQueueLaunched = false;
  11768. }
  11769. };
  11770. /**
  11771. * Register and execute a render loop. The engine can have more than one render function.
  11772. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11773. * @example
  11774. * engine.runRenderLoop(function () {
  11775. * scene.render()
  11776. * })
  11777. */
  11778. Engine.prototype.runRenderLoop = function (renderFunction) {
  11779. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11780. return;
  11781. }
  11782. this._activeRenderLoops.push(renderFunction);
  11783. if (!this._renderingQueueLaunched) {
  11784. this._renderingQueueLaunched = true;
  11785. this._bindedRenderFunction = this._renderLoop.bind(this);
  11786. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11787. }
  11788. };
  11789. /**
  11790. * Toggle full screen mode.
  11791. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11792. * @param {any} options - an options object to be sent to the requestFullscreen function
  11793. */
  11794. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11795. if (this.isFullscreen) {
  11796. BABYLON.Tools.ExitFullscreen();
  11797. }
  11798. else {
  11799. this._pointerLockRequested = requestPointerLock;
  11800. if (this._renderingCanvas) {
  11801. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11802. }
  11803. }
  11804. };
  11805. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11806. if (stencil === void 0) { stencil = false; }
  11807. this.applyStates();
  11808. var mode = 0;
  11809. if (backBuffer && color) {
  11810. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11811. mode |= this._gl.COLOR_BUFFER_BIT;
  11812. }
  11813. if (depth) {
  11814. this._gl.clearDepth(1.0);
  11815. mode |= this._gl.DEPTH_BUFFER_BIT;
  11816. }
  11817. if (stencil) {
  11818. this._gl.clearStencil(0);
  11819. mode |= this._gl.STENCIL_BUFFER_BIT;
  11820. }
  11821. this._gl.clear(mode);
  11822. };
  11823. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11824. var gl = this._gl;
  11825. // Save state
  11826. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11827. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11828. // Change state
  11829. gl.enable(gl.SCISSOR_TEST);
  11830. gl.scissor(x, y, width, height);
  11831. // Clear
  11832. this.clear(clearColor, true, true, true);
  11833. // Restore state
  11834. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11835. if (curScissor === true) {
  11836. gl.enable(gl.SCISSOR_TEST);
  11837. }
  11838. else {
  11839. gl.disable(gl.SCISSOR_TEST);
  11840. }
  11841. };
  11842. /**
  11843. * Set the WebGL's viewport
  11844. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11845. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11846. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11847. */
  11848. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11849. var width = requiredWidth || this.getRenderWidth();
  11850. var height = requiredHeight || this.getRenderHeight();
  11851. var x = viewport.x || 0;
  11852. var y = viewport.y || 0;
  11853. this._cachedViewport = viewport;
  11854. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11855. };
  11856. /**
  11857. * Directly set the WebGL Viewport
  11858. * The x, y, width & height are directly passed to the WebGL call
  11859. * @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.
  11860. */
  11861. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11862. var currentViewport = this._cachedViewport;
  11863. this._cachedViewport = null;
  11864. this._gl.viewport(x, y, width, height);
  11865. return currentViewport;
  11866. };
  11867. Engine.prototype.beginFrame = function () {
  11868. this.onBeginFrameObservable.notifyObservers(this);
  11869. this._measureFps();
  11870. };
  11871. Engine.prototype.endFrame = function () {
  11872. //force a flush in case we are using a bad OS.
  11873. if (this._badOS) {
  11874. this.flushFramebuffer();
  11875. }
  11876. //submit frame to the vr device, if enabled
  11877. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11878. // TODO: We should only submit the frame if we read frameData successfully.
  11879. this._vrDisplay.submitFrame();
  11880. }
  11881. this.onEndFrameObservable.notifyObservers(this);
  11882. };
  11883. /**
  11884. * resize the view according to the canvas' size.
  11885. * @example
  11886. * window.addEventListener("resize", function () {
  11887. * engine.resize();
  11888. * });
  11889. */
  11890. Engine.prototype.resize = function () {
  11891. // We're not resizing the size of the canvas while in VR mode & presenting
  11892. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11893. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11894. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11895. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11896. }
  11897. };
  11898. /**
  11899. * force a specific size of the canvas
  11900. * @param {number} width - the new canvas' width
  11901. * @param {number} height - the new canvas' height
  11902. */
  11903. Engine.prototype.setSize = function (width, height) {
  11904. if (!this._renderingCanvas) {
  11905. return;
  11906. }
  11907. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11908. return;
  11909. }
  11910. this._renderingCanvas.width = width;
  11911. this._renderingCanvas.height = height;
  11912. for (var index = 0; index < this.scenes.length; index++) {
  11913. var scene = this.scenes[index];
  11914. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11915. var cam = scene.cameras[camIndex];
  11916. cam._currentRenderId = 0;
  11917. }
  11918. }
  11919. if (this.onResizeObservable.hasObservers) {
  11920. this.onResizeObservable.notifyObservers(this);
  11921. }
  11922. };
  11923. // WebVR functions
  11924. Engine.prototype.isVRDevicePresent = function () {
  11925. return !!this._vrDisplay;
  11926. };
  11927. Engine.prototype.getVRDevice = function () {
  11928. return this._vrDisplay;
  11929. };
  11930. /**
  11931. * Initializes a webVR display and starts listening to display change events.
  11932. * The onVRDisplayChangedObservable will be notified upon these changes.
  11933. * @returns The onVRDisplayChangedObservable.
  11934. */
  11935. Engine.prototype.initWebVR = function () {
  11936. this.initWebVRAsync();
  11937. return this.onVRDisplayChangedObservable;
  11938. };
  11939. /**
  11940. * Initializes a webVR display and starts listening to display change events.
  11941. * The onVRDisplayChangedObservable will be notified upon these changes.
  11942. * @returns A promise containing a VRDisplay and if vr is supported.
  11943. */
  11944. Engine.prototype.initWebVRAsync = function () {
  11945. var _this = this;
  11946. var notifyObservers = function () {
  11947. var eventArgs = {
  11948. vrDisplay: _this._vrDisplay,
  11949. vrSupported: _this._vrSupported
  11950. };
  11951. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11952. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11953. };
  11954. if (!this._onVrDisplayConnect) {
  11955. this._onVrDisplayConnect = function (event) {
  11956. _this._vrDisplay = event.display;
  11957. notifyObservers();
  11958. };
  11959. this._onVrDisplayDisconnect = function () {
  11960. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11961. _this._vrDisplay = undefined;
  11962. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11963. notifyObservers();
  11964. };
  11965. this._onVrDisplayPresentChange = function () {
  11966. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11967. };
  11968. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11969. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11970. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11971. }
  11972. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11973. this._webVRInitPromise.then(notifyObservers);
  11974. return this._webVRInitPromise;
  11975. };
  11976. Engine.prototype.enableVR = function () {
  11977. var _this = this;
  11978. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11979. var onResolved = function () {
  11980. _this.onVRRequestPresentComplete.notifyObservers(true);
  11981. _this._onVRFullScreenTriggered();
  11982. };
  11983. var onRejected = function () {
  11984. _this.onVRRequestPresentComplete.notifyObservers(false);
  11985. };
  11986. this.onVRRequestPresentStart.notifyObservers(this);
  11987. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11988. }
  11989. };
  11990. Engine.prototype.disableVR = function () {
  11991. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11992. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11993. }
  11994. };
  11995. Engine.prototype._getVRDisplaysAsync = function () {
  11996. var _this = this;
  11997. return new Promise(function (res, rej) {
  11998. if (navigator.getVRDisplays) {
  11999. navigator.getVRDisplays().then(function (devices) {
  12000. _this._vrSupported = true;
  12001. // note that devices may actually be an empty array. This is fine;
  12002. // we expect this._vrDisplay to be undefined in this case.
  12003. _this._vrDisplay = devices[0];
  12004. res({
  12005. vrDisplay: _this._vrDisplay,
  12006. vrSupported: _this._vrSupported
  12007. });
  12008. });
  12009. }
  12010. else {
  12011. _this._vrDisplay = undefined;
  12012. _this._vrSupported = false;
  12013. res({
  12014. vrDisplay: _this._vrDisplay,
  12015. vrSupported: _this._vrSupported
  12016. });
  12017. }
  12018. });
  12019. };
  12020. /**
  12021. * Binds the frame buffer to the specified texture.
  12022. * @param texture The texture to render to or null for the default canvas
  12023. * @param faceIndex The face of the texture to render to in case of cube texture
  12024. * @param requiredWidth The width of the target to render to
  12025. * @param requiredHeight The height of the target to render to
  12026. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12027. * @param depthStencilTexture The depth stencil texture to use to render
  12028. */
  12029. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12030. if (this._currentRenderTarget) {
  12031. this.unBindFramebuffer(this._currentRenderTarget);
  12032. }
  12033. this._currentRenderTarget = texture;
  12034. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12035. var gl = this._gl;
  12036. if (texture.isCube) {
  12037. if (faceIndex === undefined) {
  12038. faceIndex = 0;
  12039. }
  12040. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12041. if (depthStencilTexture) {
  12042. if (depthStencilTexture._generateStencilBuffer) {
  12043. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12044. }
  12045. else {
  12046. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12047. }
  12048. }
  12049. }
  12050. if (this._cachedViewport && !forceFullscreenViewport) {
  12051. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12052. }
  12053. else {
  12054. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12055. }
  12056. this.wipeCaches();
  12057. };
  12058. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12059. if (this._currentFramebuffer !== framebuffer) {
  12060. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12061. this._currentFramebuffer = framebuffer;
  12062. }
  12063. };
  12064. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12065. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12066. this._currentRenderTarget = null;
  12067. // If MSAA, we need to bitblt back to main texture
  12068. var gl = this._gl;
  12069. if (texture._MSAAFramebuffer) {
  12070. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12071. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12072. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12073. }
  12074. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12075. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12076. gl.generateMipmap(gl.TEXTURE_2D);
  12077. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12078. }
  12079. if (onBeforeUnbind) {
  12080. if (texture._MSAAFramebuffer) {
  12081. // Bind the correct framebuffer
  12082. this.bindUnboundFramebuffer(texture._framebuffer);
  12083. }
  12084. onBeforeUnbind();
  12085. }
  12086. this.bindUnboundFramebuffer(null);
  12087. };
  12088. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12089. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12090. this._currentRenderTarget = null;
  12091. // If MSAA, we need to bitblt back to main texture
  12092. var gl = this._gl;
  12093. if (textures[0]._MSAAFramebuffer) {
  12094. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12095. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12096. var attachments = textures[0]._attachments;
  12097. if (!attachments) {
  12098. attachments = new Array(textures.length);
  12099. textures[0]._attachments = attachments;
  12100. }
  12101. for (var i = 0; i < textures.length; i++) {
  12102. var texture = textures[i];
  12103. for (var j = 0; j < attachments.length; j++) {
  12104. attachments[j] = gl.NONE;
  12105. }
  12106. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12107. gl.readBuffer(attachments[i]);
  12108. gl.drawBuffers(attachments);
  12109. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12110. }
  12111. for (var i = 0; i < attachments.length; i++) {
  12112. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12113. }
  12114. gl.drawBuffers(attachments);
  12115. }
  12116. for (var i = 0; i < textures.length; i++) {
  12117. var texture = textures[i];
  12118. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12119. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12120. gl.generateMipmap(gl.TEXTURE_2D);
  12121. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12122. }
  12123. }
  12124. if (onBeforeUnbind) {
  12125. if (textures[0]._MSAAFramebuffer) {
  12126. // Bind the correct framebuffer
  12127. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12128. }
  12129. onBeforeUnbind();
  12130. }
  12131. this.bindUnboundFramebuffer(null);
  12132. };
  12133. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12134. if (texture.generateMipMaps) {
  12135. var gl = this._gl;
  12136. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12137. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12138. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12139. }
  12140. };
  12141. Engine.prototype.flushFramebuffer = function () {
  12142. this._gl.flush();
  12143. };
  12144. Engine.prototype.restoreDefaultFramebuffer = function () {
  12145. if (this._currentRenderTarget) {
  12146. this.unBindFramebuffer(this._currentRenderTarget);
  12147. }
  12148. else {
  12149. this.bindUnboundFramebuffer(null);
  12150. }
  12151. if (this._cachedViewport) {
  12152. this.setViewport(this._cachedViewport);
  12153. }
  12154. this.wipeCaches();
  12155. };
  12156. // UBOs
  12157. Engine.prototype.createUniformBuffer = function (elements) {
  12158. var ubo = this._gl.createBuffer();
  12159. if (!ubo) {
  12160. throw new Error("Unable to create uniform buffer");
  12161. }
  12162. this.bindUniformBuffer(ubo);
  12163. if (elements instanceof Float32Array) {
  12164. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12165. }
  12166. else {
  12167. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12168. }
  12169. this.bindUniformBuffer(null);
  12170. ubo.references = 1;
  12171. return ubo;
  12172. };
  12173. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12174. var ubo = this._gl.createBuffer();
  12175. if (!ubo) {
  12176. throw new Error("Unable to create dynamic uniform buffer");
  12177. }
  12178. this.bindUniformBuffer(ubo);
  12179. if (elements instanceof Float32Array) {
  12180. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12181. }
  12182. else {
  12183. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12184. }
  12185. this.bindUniformBuffer(null);
  12186. ubo.references = 1;
  12187. return ubo;
  12188. };
  12189. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12190. this.bindUniformBuffer(uniformBuffer);
  12191. if (offset === undefined) {
  12192. offset = 0;
  12193. }
  12194. if (count === undefined) {
  12195. if (elements instanceof Float32Array) {
  12196. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12197. }
  12198. else {
  12199. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12200. }
  12201. }
  12202. else {
  12203. if (elements instanceof Float32Array) {
  12204. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12205. }
  12206. else {
  12207. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12208. }
  12209. }
  12210. this.bindUniformBuffer(null);
  12211. };
  12212. // VBOs
  12213. Engine.prototype._resetVertexBufferBinding = function () {
  12214. this.bindArrayBuffer(null);
  12215. this._cachedVertexBuffers = null;
  12216. };
  12217. Engine.prototype.createVertexBuffer = function (vertices) {
  12218. var vbo = this._gl.createBuffer();
  12219. if (!vbo) {
  12220. throw new Error("Unable to create vertex buffer");
  12221. }
  12222. this.bindArrayBuffer(vbo);
  12223. if (vertices instanceof Float32Array) {
  12224. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12225. }
  12226. else {
  12227. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12228. }
  12229. this._resetVertexBufferBinding();
  12230. vbo.references = 1;
  12231. return vbo;
  12232. };
  12233. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12234. var vbo = this._gl.createBuffer();
  12235. if (!vbo) {
  12236. throw new Error("Unable to create dynamic vertex buffer");
  12237. }
  12238. this.bindArrayBuffer(vbo);
  12239. if (vertices instanceof Float32Array) {
  12240. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12241. }
  12242. else {
  12243. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12244. }
  12245. this._resetVertexBufferBinding();
  12246. vbo.references = 1;
  12247. return vbo;
  12248. };
  12249. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12250. if (offset === void 0) { offset = 0; }
  12251. // Force cache update
  12252. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12253. this.bindIndexBuffer(indexBuffer);
  12254. var arrayBuffer;
  12255. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12256. arrayBuffer = indices;
  12257. }
  12258. else {
  12259. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12260. }
  12261. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12262. this._resetIndexBufferBinding();
  12263. };
  12264. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12265. this.bindArrayBuffer(vertexBuffer);
  12266. if (offset === undefined) {
  12267. offset = 0;
  12268. }
  12269. if (count === undefined) {
  12270. if (vertices instanceof Float32Array) {
  12271. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12272. }
  12273. else {
  12274. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12275. }
  12276. }
  12277. else {
  12278. if (vertices instanceof Float32Array) {
  12279. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12280. }
  12281. else {
  12282. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12283. }
  12284. }
  12285. this._resetVertexBufferBinding();
  12286. };
  12287. Engine.prototype._resetIndexBufferBinding = function () {
  12288. this.bindIndexBuffer(null);
  12289. this._cachedIndexBuffer = null;
  12290. };
  12291. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12292. var vbo = this._gl.createBuffer();
  12293. if (!vbo) {
  12294. throw new Error("Unable to create index buffer");
  12295. }
  12296. this.bindIndexBuffer(vbo);
  12297. // Check for 32 bits indices
  12298. var arrayBuffer;
  12299. var need32Bits = false;
  12300. if (indices instanceof Uint16Array) {
  12301. arrayBuffer = indices;
  12302. }
  12303. else {
  12304. //check 32 bit support
  12305. if (this._caps.uintIndices) {
  12306. if (indices instanceof Uint32Array) {
  12307. arrayBuffer = indices;
  12308. need32Bits = true;
  12309. }
  12310. else {
  12311. //number[] or Int32Array, check if 32 bit is necessary
  12312. for (var index = 0; index < indices.length; index++) {
  12313. if (indices[index] > 65535) {
  12314. need32Bits = true;
  12315. break;
  12316. }
  12317. }
  12318. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12319. }
  12320. }
  12321. else {
  12322. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12323. arrayBuffer = new Uint16Array(indices);
  12324. }
  12325. }
  12326. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12327. this._resetIndexBufferBinding();
  12328. vbo.references = 1;
  12329. vbo.is32Bits = need32Bits;
  12330. return vbo;
  12331. };
  12332. Engine.prototype.bindArrayBuffer = function (buffer) {
  12333. if (!this._vaoRecordInProgress) {
  12334. this._unbindVertexArrayObject();
  12335. }
  12336. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12337. };
  12338. Engine.prototype.bindUniformBuffer = function (buffer) {
  12339. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12340. };
  12341. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12342. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12343. };
  12344. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12345. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12346. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12347. };
  12348. ;
  12349. Engine.prototype.bindIndexBuffer = function (buffer) {
  12350. if (!this._vaoRecordInProgress) {
  12351. this._unbindVertexArrayObject();
  12352. }
  12353. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12354. };
  12355. Engine.prototype.bindBuffer = function (buffer, target) {
  12356. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12357. this._gl.bindBuffer(target, buffer);
  12358. this._currentBoundBuffer[target] = buffer;
  12359. }
  12360. };
  12361. Engine.prototype.updateArrayBuffer = function (data) {
  12362. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12363. };
  12364. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12365. var pointer = this._currentBufferPointers[indx];
  12366. var changed = false;
  12367. if (!pointer.active) {
  12368. changed = true;
  12369. pointer.active = true;
  12370. pointer.index = indx;
  12371. pointer.size = size;
  12372. pointer.type = type;
  12373. pointer.normalized = normalized;
  12374. pointer.stride = stride;
  12375. pointer.offset = offset;
  12376. pointer.buffer = buffer;
  12377. }
  12378. else {
  12379. if (pointer.buffer !== buffer) {
  12380. pointer.buffer = buffer;
  12381. changed = true;
  12382. }
  12383. if (pointer.size !== size) {
  12384. pointer.size = size;
  12385. changed = true;
  12386. }
  12387. if (pointer.type !== type) {
  12388. pointer.type = type;
  12389. changed = true;
  12390. }
  12391. if (pointer.normalized !== normalized) {
  12392. pointer.normalized = normalized;
  12393. changed = true;
  12394. }
  12395. if (pointer.stride !== stride) {
  12396. pointer.stride = stride;
  12397. changed = true;
  12398. }
  12399. if (pointer.offset !== offset) {
  12400. pointer.offset = offset;
  12401. changed = true;
  12402. }
  12403. }
  12404. if (changed || this._vaoRecordInProgress) {
  12405. this.bindArrayBuffer(buffer);
  12406. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12407. }
  12408. };
  12409. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12410. if (indexBuffer == null) {
  12411. return;
  12412. }
  12413. if (this._cachedIndexBuffer !== indexBuffer) {
  12414. this._cachedIndexBuffer = indexBuffer;
  12415. this.bindIndexBuffer(indexBuffer);
  12416. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12417. }
  12418. };
  12419. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12420. var attributes = effect.getAttributesNames();
  12421. if (!this._vaoRecordInProgress) {
  12422. this._unbindVertexArrayObject();
  12423. }
  12424. this.unbindAllAttributes();
  12425. for (var index = 0; index < attributes.length; index++) {
  12426. var order = effect.getAttributeLocation(index);
  12427. if (order >= 0) {
  12428. var vertexBuffer = vertexBuffers[attributes[index]];
  12429. if (!vertexBuffer) {
  12430. continue;
  12431. }
  12432. this._gl.enableVertexAttribArray(order);
  12433. if (!this._vaoRecordInProgress) {
  12434. this._vertexAttribArraysEnabled[order] = true;
  12435. }
  12436. var buffer = vertexBuffer.getBuffer();
  12437. if (buffer) {
  12438. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12439. if (vertexBuffer.getIsInstanced()) {
  12440. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12441. if (!this._vaoRecordInProgress) {
  12442. this._currentInstanceLocations.push(order);
  12443. this._currentInstanceBuffers.push(buffer);
  12444. }
  12445. }
  12446. }
  12447. }
  12448. }
  12449. };
  12450. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12451. var vao = this._gl.createVertexArray();
  12452. this._vaoRecordInProgress = true;
  12453. this._gl.bindVertexArray(vao);
  12454. this._mustWipeVertexAttributes = true;
  12455. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12456. this.bindIndexBuffer(indexBuffer);
  12457. this._vaoRecordInProgress = false;
  12458. this._gl.bindVertexArray(null);
  12459. return vao;
  12460. };
  12461. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12462. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12463. this._cachedVertexArrayObject = vertexArrayObject;
  12464. this._gl.bindVertexArray(vertexArrayObject);
  12465. this._cachedVertexBuffers = null;
  12466. this._cachedIndexBuffer = null;
  12467. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12468. this._mustWipeVertexAttributes = true;
  12469. }
  12470. };
  12471. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12472. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12473. this._cachedVertexBuffers = vertexBuffer;
  12474. this._cachedEffectForVertexBuffers = effect;
  12475. var attributesCount = effect.getAttributesCount();
  12476. this._unbindVertexArrayObject();
  12477. this.unbindAllAttributes();
  12478. var offset = 0;
  12479. for (var index = 0; index < attributesCount; index++) {
  12480. if (index < vertexDeclaration.length) {
  12481. var order = effect.getAttributeLocation(index);
  12482. if (order >= 0) {
  12483. this._gl.enableVertexAttribArray(order);
  12484. this._vertexAttribArraysEnabled[order] = true;
  12485. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12486. }
  12487. offset += vertexDeclaration[index] * 4;
  12488. }
  12489. }
  12490. }
  12491. this._bindIndexBufferWithCache(indexBuffer);
  12492. };
  12493. Engine.prototype._unbindVertexArrayObject = function () {
  12494. if (!this._cachedVertexArrayObject) {
  12495. return;
  12496. }
  12497. this._cachedVertexArrayObject = null;
  12498. this._gl.bindVertexArray(null);
  12499. };
  12500. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12501. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12502. this._cachedVertexBuffers = vertexBuffers;
  12503. this._cachedEffectForVertexBuffers = effect;
  12504. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12505. }
  12506. this._bindIndexBufferWithCache(indexBuffer);
  12507. };
  12508. Engine.prototype.unbindInstanceAttributes = function () {
  12509. var boundBuffer;
  12510. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12511. var instancesBuffer = this._currentInstanceBuffers[i];
  12512. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12513. boundBuffer = instancesBuffer;
  12514. this.bindArrayBuffer(instancesBuffer);
  12515. }
  12516. var offsetLocation = this._currentInstanceLocations[i];
  12517. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12518. }
  12519. this._currentInstanceBuffers.length = 0;
  12520. this._currentInstanceLocations.length = 0;
  12521. };
  12522. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12523. this._gl.deleteVertexArray(vao);
  12524. };
  12525. Engine.prototype._releaseBuffer = function (buffer) {
  12526. buffer.references--;
  12527. if (buffer.references === 0) {
  12528. this._gl.deleteBuffer(buffer);
  12529. return true;
  12530. }
  12531. return false;
  12532. };
  12533. Engine.prototype.createInstancesBuffer = function (capacity) {
  12534. var buffer = this._gl.createBuffer();
  12535. if (!buffer) {
  12536. throw new Error("Unable to create instance buffer");
  12537. }
  12538. buffer.capacity = capacity;
  12539. this.bindArrayBuffer(buffer);
  12540. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12541. return buffer;
  12542. };
  12543. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12544. this._gl.deleteBuffer(buffer);
  12545. };
  12546. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12547. this.bindArrayBuffer(instancesBuffer);
  12548. if (data) {
  12549. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12550. }
  12551. if (offsetLocations[0].index !== undefined) {
  12552. var stride = 0;
  12553. for (var i = 0; i < offsetLocations.length; i++) {
  12554. var ai = offsetLocations[i];
  12555. stride += ai.attributeSize * 4;
  12556. }
  12557. for (var i = 0; i < offsetLocations.length; i++) {
  12558. var ai = offsetLocations[i];
  12559. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12560. this._gl.enableVertexAttribArray(ai.index);
  12561. this._vertexAttribArraysEnabled[ai.index] = true;
  12562. }
  12563. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12564. this._gl.vertexAttribDivisor(ai.index, 1);
  12565. this._currentInstanceLocations.push(ai.index);
  12566. this._currentInstanceBuffers.push(instancesBuffer);
  12567. }
  12568. }
  12569. else {
  12570. for (var index = 0; index < 4; index++) {
  12571. var offsetLocation = offsetLocations[index];
  12572. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12573. this._gl.enableVertexAttribArray(offsetLocation);
  12574. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12575. }
  12576. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12577. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12578. this._currentInstanceLocations.push(offsetLocation);
  12579. this._currentInstanceBuffers.push(instancesBuffer);
  12580. }
  12581. }
  12582. };
  12583. Engine.prototype.applyStates = function () {
  12584. this._depthCullingState.apply(this._gl);
  12585. this._stencilState.apply(this._gl);
  12586. this._alphaState.apply(this._gl);
  12587. };
  12588. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12589. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12590. };
  12591. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12592. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12593. };
  12594. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12595. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12596. };
  12597. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12598. // Apply states
  12599. this.applyStates();
  12600. this._drawCalls.addCount(1, false);
  12601. // Render
  12602. var drawMode = this._drawMode(fillMode);
  12603. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12604. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12605. if (instancesCount) {
  12606. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12607. }
  12608. else {
  12609. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12610. }
  12611. };
  12612. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12613. // Apply states
  12614. this.applyStates();
  12615. this._drawCalls.addCount(1, false);
  12616. var drawMode = this._drawMode(fillMode);
  12617. if (instancesCount) {
  12618. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12619. }
  12620. else {
  12621. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12622. }
  12623. };
  12624. Engine.prototype._drawMode = function (fillMode) {
  12625. switch (fillMode) {
  12626. // Triangle views
  12627. case BABYLON.Material.TriangleFillMode:
  12628. return this._gl.TRIANGLES;
  12629. case BABYLON.Material.PointFillMode:
  12630. return this._gl.POINTS;
  12631. case BABYLON.Material.WireFrameFillMode:
  12632. return this._gl.LINES;
  12633. // Draw modes
  12634. case BABYLON.Material.PointListDrawMode:
  12635. return this._gl.POINTS;
  12636. case BABYLON.Material.LineListDrawMode:
  12637. return this._gl.LINES;
  12638. case BABYLON.Material.LineLoopDrawMode:
  12639. return this._gl.LINE_LOOP;
  12640. case BABYLON.Material.LineStripDrawMode:
  12641. return this._gl.LINE_STRIP;
  12642. case BABYLON.Material.TriangleStripDrawMode:
  12643. return this._gl.TRIANGLE_STRIP;
  12644. case BABYLON.Material.TriangleFanDrawMode:
  12645. return this._gl.TRIANGLE_FAN;
  12646. default:
  12647. return this._gl.TRIANGLES;
  12648. }
  12649. };
  12650. // Shaders
  12651. Engine.prototype._releaseEffect = function (effect) {
  12652. if (this._compiledEffects[effect._key]) {
  12653. delete this._compiledEffects[effect._key];
  12654. this._deleteProgram(effect.getProgram());
  12655. }
  12656. };
  12657. Engine.prototype._deleteProgram = function (program) {
  12658. if (program) {
  12659. program.__SPECTOR_rebuildProgram = null;
  12660. if (program.transformFeedback) {
  12661. this.deleteTransformFeedback(program.transformFeedback);
  12662. program.transformFeedback = null;
  12663. }
  12664. this._gl.deleteProgram(program);
  12665. }
  12666. };
  12667. /**
  12668. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12669. * @param samplers An array of string used to represent textures
  12670. */
  12671. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12672. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12673. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12674. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12675. if (this._compiledEffects[name]) {
  12676. var compiledEffect = this._compiledEffects[name];
  12677. if (onCompiled && compiledEffect.isReady()) {
  12678. onCompiled(compiledEffect);
  12679. }
  12680. return compiledEffect;
  12681. }
  12682. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12683. effect._key = name;
  12684. this._compiledEffects[name] = effect;
  12685. return effect;
  12686. };
  12687. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12688. if (uniformsNames === void 0) { uniformsNames = []; }
  12689. if (samplers === void 0) { samplers = []; }
  12690. if (defines === void 0) { defines = ""; }
  12691. return this.createEffect({
  12692. vertex: "particles",
  12693. fragmentElement: fragmentName
  12694. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12695. };
  12696. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12697. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12698. context = context || this._gl;
  12699. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12700. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12701. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12702. };
  12703. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12704. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12705. context = context || this._gl;
  12706. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12707. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12708. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12709. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12710. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12711. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12712. return program;
  12713. };
  12714. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12715. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12716. var shaderProgram = context.createProgram();
  12717. if (!shaderProgram) {
  12718. throw new Error("Unable to create program");
  12719. }
  12720. context.attachShader(shaderProgram, vertexShader);
  12721. context.attachShader(shaderProgram, fragmentShader);
  12722. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12723. var transformFeedback = this.createTransformFeedback();
  12724. this.bindTransformFeedback(transformFeedback);
  12725. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12726. shaderProgram.transformFeedback = transformFeedback;
  12727. }
  12728. context.linkProgram(shaderProgram);
  12729. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12730. this.bindTransformFeedback(null);
  12731. }
  12732. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12733. if (!linked) {
  12734. context.validateProgram(shaderProgram);
  12735. var error = context.getProgramInfoLog(shaderProgram);
  12736. if (error) {
  12737. throw new Error(error);
  12738. }
  12739. }
  12740. context.deleteShader(vertexShader);
  12741. context.deleteShader(fragmentShader);
  12742. return shaderProgram;
  12743. };
  12744. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12745. var results = new Array();
  12746. for (var index = 0; index < uniformsNames.length; index++) {
  12747. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12748. }
  12749. return results;
  12750. };
  12751. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12752. var results = [];
  12753. for (var index = 0; index < attributesNames.length; index++) {
  12754. try {
  12755. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12756. }
  12757. catch (e) {
  12758. results.push(-1);
  12759. }
  12760. }
  12761. return results;
  12762. };
  12763. Engine.prototype.enableEffect = function (effect) {
  12764. if (!effect) {
  12765. return;
  12766. }
  12767. // Use program
  12768. this.bindSamplers(effect);
  12769. this._currentEffect = effect;
  12770. if (effect.onBind) {
  12771. effect.onBind(effect);
  12772. }
  12773. effect.onBindObservable.notifyObservers(effect);
  12774. };
  12775. Engine.prototype.setIntArray = function (uniform, array) {
  12776. if (!uniform)
  12777. return;
  12778. this._gl.uniform1iv(uniform, array);
  12779. };
  12780. Engine.prototype.setIntArray2 = function (uniform, array) {
  12781. if (!uniform || array.length % 2 !== 0)
  12782. return;
  12783. this._gl.uniform2iv(uniform, array);
  12784. };
  12785. Engine.prototype.setIntArray3 = function (uniform, array) {
  12786. if (!uniform || array.length % 3 !== 0)
  12787. return;
  12788. this._gl.uniform3iv(uniform, array);
  12789. };
  12790. Engine.prototype.setIntArray4 = function (uniform, array) {
  12791. if (!uniform || array.length % 4 !== 0)
  12792. return;
  12793. this._gl.uniform4iv(uniform, array);
  12794. };
  12795. Engine.prototype.setFloatArray = function (uniform, array) {
  12796. if (!uniform)
  12797. return;
  12798. this._gl.uniform1fv(uniform, array);
  12799. };
  12800. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12801. if (!uniform || array.length % 2 !== 0)
  12802. return;
  12803. this._gl.uniform2fv(uniform, array);
  12804. };
  12805. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12806. if (!uniform || array.length % 3 !== 0)
  12807. return;
  12808. this._gl.uniform3fv(uniform, array);
  12809. };
  12810. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12811. if (!uniform || array.length % 4 !== 0)
  12812. return;
  12813. this._gl.uniform4fv(uniform, array);
  12814. };
  12815. Engine.prototype.setArray = function (uniform, array) {
  12816. if (!uniform)
  12817. return;
  12818. this._gl.uniform1fv(uniform, array);
  12819. };
  12820. Engine.prototype.setArray2 = function (uniform, array) {
  12821. if (!uniform || array.length % 2 !== 0)
  12822. return;
  12823. this._gl.uniform2fv(uniform, array);
  12824. };
  12825. Engine.prototype.setArray3 = function (uniform, array) {
  12826. if (!uniform || array.length % 3 !== 0)
  12827. return;
  12828. this._gl.uniform3fv(uniform, array);
  12829. };
  12830. Engine.prototype.setArray4 = function (uniform, array) {
  12831. if (!uniform || array.length % 4 !== 0)
  12832. return;
  12833. this._gl.uniform4fv(uniform, array);
  12834. };
  12835. Engine.prototype.setMatrices = function (uniform, matrices) {
  12836. if (!uniform)
  12837. return;
  12838. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12839. };
  12840. Engine.prototype.setMatrix = function (uniform, matrix) {
  12841. if (!uniform)
  12842. return;
  12843. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12844. };
  12845. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12846. if (!uniform)
  12847. return;
  12848. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12849. };
  12850. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12851. if (!uniform)
  12852. return;
  12853. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12854. };
  12855. Engine.prototype.setInt = function (uniform, value) {
  12856. if (!uniform)
  12857. return;
  12858. this._gl.uniform1i(uniform, value);
  12859. };
  12860. Engine.prototype.setFloat = function (uniform, value) {
  12861. if (!uniform)
  12862. return;
  12863. this._gl.uniform1f(uniform, value);
  12864. };
  12865. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12866. if (!uniform)
  12867. return;
  12868. this._gl.uniform2f(uniform, x, y);
  12869. };
  12870. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12871. if (!uniform)
  12872. return;
  12873. this._gl.uniform3f(uniform, x, y, z);
  12874. };
  12875. Engine.prototype.setBool = function (uniform, bool) {
  12876. if (!uniform)
  12877. return;
  12878. this._gl.uniform1i(uniform, bool);
  12879. };
  12880. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12881. if (!uniform)
  12882. return;
  12883. this._gl.uniform4f(uniform, x, y, z, w);
  12884. };
  12885. Engine.prototype.setColor3 = function (uniform, color3) {
  12886. if (!uniform)
  12887. return;
  12888. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12889. };
  12890. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12891. if (!uniform)
  12892. return;
  12893. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12894. };
  12895. /**
  12896. * Sets a Color4 on a uniform variable
  12897. * @param uniform defines the uniform location
  12898. * @param color4 defines the value to be set
  12899. */
  12900. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12901. if (!uniform)
  12902. return;
  12903. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12904. };
  12905. // States
  12906. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12907. if (zOffset === void 0) { zOffset = 0; }
  12908. if (reverseSide === void 0) { reverseSide = false; }
  12909. // Culling
  12910. if (this._depthCullingState.cull !== culling || force) {
  12911. this._depthCullingState.cull = culling;
  12912. }
  12913. // Cull face
  12914. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12915. if (this._depthCullingState.cullFace !== cullFace || force) {
  12916. this._depthCullingState.cullFace = cullFace;
  12917. }
  12918. // Z offset
  12919. this.setZOffset(zOffset);
  12920. // Front face
  12921. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12922. if (this._depthCullingState.frontFace !== frontFace || force) {
  12923. this._depthCullingState.frontFace = frontFace;
  12924. }
  12925. };
  12926. Engine.prototype.setZOffset = function (value) {
  12927. this._depthCullingState.zOffset = value;
  12928. };
  12929. Engine.prototype.getZOffset = function () {
  12930. return this._depthCullingState.zOffset;
  12931. };
  12932. Engine.prototype.setDepthBuffer = function (enable) {
  12933. this._depthCullingState.depthTest = enable;
  12934. };
  12935. Engine.prototype.getDepthWrite = function () {
  12936. return this._depthCullingState.depthMask;
  12937. };
  12938. Engine.prototype.setDepthWrite = function (enable) {
  12939. this._depthCullingState.depthMask = enable;
  12940. };
  12941. Engine.prototype.setColorWrite = function (enable) {
  12942. this._gl.colorMask(enable, enable, enable, enable);
  12943. this._colorWrite = enable;
  12944. };
  12945. Engine.prototype.getColorWrite = function () {
  12946. return this._colorWrite;
  12947. };
  12948. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12949. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12950. };
  12951. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12952. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12953. if (this._alphaMode === mode) {
  12954. return;
  12955. }
  12956. switch (mode) {
  12957. case Engine.ALPHA_DISABLE:
  12958. this._alphaState.alphaBlend = false;
  12959. break;
  12960. case Engine.ALPHA_PREMULTIPLIED:
  12961. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12962. this._alphaState.alphaBlend = true;
  12963. break;
  12964. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12965. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12966. this._alphaState.alphaBlend = true;
  12967. break;
  12968. case Engine.ALPHA_COMBINE:
  12969. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12970. this._alphaState.alphaBlend = true;
  12971. break;
  12972. case Engine.ALPHA_ONEONE:
  12973. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12974. this._alphaState.alphaBlend = true;
  12975. break;
  12976. case Engine.ALPHA_ADD:
  12977. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12978. this._alphaState.alphaBlend = true;
  12979. break;
  12980. case Engine.ALPHA_SUBTRACT:
  12981. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12982. this._alphaState.alphaBlend = true;
  12983. break;
  12984. case Engine.ALPHA_MULTIPLY:
  12985. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12986. this._alphaState.alphaBlend = true;
  12987. break;
  12988. case Engine.ALPHA_MAXIMIZED:
  12989. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12990. this._alphaState.alphaBlend = true;
  12991. break;
  12992. case Engine.ALPHA_INTERPOLATE:
  12993. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12994. this._alphaState.alphaBlend = true;
  12995. break;
  12996. case Engine.ALPHA_SCREENMODE:
  12997. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12998. this._alphaState.alphaBlend = true;
  12999. break;
  13000. }
  13001. if (!noDepthWriteChange) {
  13002. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  13003. }
  13004. this._alphaMode = mode;
  13005. };
  13006. Engine.prototype.getAlphaMode = function () {
  13007. return this._alphaMode;
  13008. };
  13009. // Textures
  13010. Engine.prototype.wipeCaches = function (bruteForce) {
  13011. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13012. return;
  13013. }
  13014. this._currentEffect = null;
  13015. // 6/8/2017: deltakosh: Should not be required anymore.
  13016. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  13017. if (bruteForce) {
  13018. this.resetTextureCache();
  13019. this._currentProgram = null;
  13020. this._stencilState.reset();
  13021. this._depthCullingState.reset();
  13022. this.setDepthFunctionToLessOrEqual();
  13023. this._alphaState.reset();
  13024. }
  13025. this._resetVertexBufferBinding();
  13026. this._cachedIndexBuffer = null;
  13027. this._cachedEffectForVertexBuffers = null;
  13028. this._unbindVertexArrayObject();
  13029. this.bindIndexBuffer(null);
  13030. };
  13031. /**
  13032. * Set the compressed texture format to use, based on the formats you have, and the formats
  13033. * supported by the hardware / browser.
  13034. *
  13035. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13036. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13037. * to API arguments needed to compressed textures. This puts the burden on the container
  13038. * generator to house the arcane code for determining these for current & future formats.
  13039. *
  13040. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13041. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13042. *
  13043. * Note: The result of this call is not taken into account when a texture is base64.
  13044. *
  13045. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13046. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13047. *
  13048. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13049. * @returns The extension selected.
  13050. */
  13051. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13052. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13053. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13054. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13055. return this._textureFormatInUse = this._texturesSupported[i];
  13056. }
  13057. }
  13058. }
  13059. // actively set format to nothing, to allow this to be called more than once
  13060. // and possibly fail the 2nd time
  13061. this._textureFormatInUse = null;
  13062. return null;
  13063. };
  13064. Engine.prototype._createTexture = function () {
  13065. var texture = this._gl.createTexture();
  13066. if (!texture) {
  13067. throw new Error("Unable to create texture");
  13068. }
  13069. return texture;
  13070. };
  13071. /**
  13072. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13073. * @param {string} urlArg- This contains one of the following:
  13074. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13075. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13076. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13077. *
  13078. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13079. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13080. * @param {Scene} scene- Needed for loading to the correct scene.
  13081. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13082. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13083. * @param {callback} onError- Optional callback to be called upon failure.
  13084. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13085. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13086. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13087. *
  13088. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13089. */
  13090. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13091. var _this = this;
  13092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13093. if (onLoad === void 0) { onLoad = null; }
  13094. if (onError === void 0) { onError = null; }
  13095. if (buffer === void 0) { buffer = null; }
  13096. if (fallBack === void 0) { fallBack = null; }
  13097. if (format === void 0) { format = null; }
  13098. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13099. var fromData = url.substr(0, 5) === "data:";
  13100. var fromBlob = url.substr(0, 5) === "blob:";
  13101. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13102. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13103. // establish the file extension, if possible
  13104. var lastDot = url.lastIndexOf('.');
  13105. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13106. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13107. var isTGA = (extension.indexOf(".tga") === 0);
  13108. // determine if a ktx file should be substituted
  13109. var isKTX = false;
  13110. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13111. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13112. isKTX = true;
  13113. }
  13114. if (scene) {
  13115. scene._addPendingData(texture);
  13116. }
  13117. texture.url = url;
  13118. texture.generateMipMaps = !noMipmap;
  13119. texture.samplingMode = samplingMode;
  13120. texture.invertY = invertY;
  13121. if (!this._doNotHandleContextLost) {
  13122. // Keep a link to the buffer only if we plan to handle context lost
  13123. texture._buffer = buffer;
  13124. }
  13125. var onLoadObserver = null;
  13126. if (onLoad && !fallBack) {
  13127. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13128. }
  13129. if (!fallBack)
  13130. this._internalTexturesCache.push(texture);
  13131. var onerror = function (message, exception) {
  13132. if (scene) {
  13133. scene._removePendingData(texture);
  13134. }
  13135. if (onLoadObserver) {
  13136. texture.onLoadedObservable.remove(onLoadObserver);
  13137. }
  13138. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13139. if (isKTX) {
  13140. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13141. }
  13142. else if (BABYLON.Tools.UseFallbackTexture) {
  13143. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13144. }
  13145. if (onError) {
  13146. onError(message || "Unknown error", exception);
  13147. }
  13148. };
  13149. var callback = null;
  13150. // processing for non-image formats
  13151. if (isKTX || isTGA || isDDS) {
  13152. if (isKTX) {
  13153. callback = function (data) {
  13154. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13155. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13156. ktx.uploadLevels(_this._gl, !noMipmap);
  13157. return false;
  13158. }, samplingMode);
  13159. };
  13160. }
  13161. else if (isTGA) {
  13162. callback = function (arrayBuffer) {
  13163. var data = new Uint8Array(arrayBuffer);
  13164. var header = BABYLON.TGATools.GetTGAHeader(data);
  13165. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13166. BABYLON.TGATools.UploadContent(_this._gl, data);
  13167. return false;
  13168. }, samplingMode);
  13169. };
  13170. }
  13171. else if (isDDS) {
  13172. callback = function (data) {
  13173. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13174. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13175. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13176. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13177. return false;
  13178. }, samplingMode);
  13179. };
  13180. }
  13181. if (!buffer) {
  13182. this._loadFile(url, function (data) {
  13183. if (callback) {
  13184. callback(data);
  13185. }
  13186. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13187. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13188. });
  13189. }
  13190. else {
  13191. if (callback) {
  13192. callback(buffer);
  13193. }
  13194. }
  13195. // image format processing
  13196. }
  13197. else {
  13198. var onload = function (img) {
  13199. if (fromBlob && !_this._doNotHandleContextLost) {
  13200. // We need to store the image if we need to rebuild the texture
  13201. // in case of a webgl context lost
  13202. texture._buffer = img;
  13203. }
  13204. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13205. var gl = _this._gl;
  13206. var isPot = (img.width === potWidth && img.height === potHeight);
  13207. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13208. if (isPot) {
  13209. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13210. return false;
  13211. }
  13212. // Using shaders to rescale because canvas.drawImage is lossy
  13213. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13214. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13215. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13216. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13219. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13220. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13221. _this._releaseTexture(source);
  13222. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13223. continuationCallback();
  13224. });
  13225. return true;
  13226. }, samplingMode);
  13227. };
  13228. if (!fromData || isBase64)
  13229. if (buffer instanceof HTMLImageElement) {
  13230. onload(buffer);
  13231. }
  13232. else {
  13233. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13234. }
  13235. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13236. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13237. else
  13238. onload(buffer);
  13239. }
  13240. return texture;
  13241. };
  13242. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13243. var _this = this;
  13244. var rtt = this.createRenderTargetTexture({
  13245. width: destination.width,
  13246. height: destination.height,
  13247. }, {
  13248. generateMipMaps: false,
  13249. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13250. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13251. generateDepthBuffer: false,
  13252. generateStencilBuffer: false
  13253. });
  13254. if (!this._rescalePostProcess) {
  13255. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13256. }
  13257. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13258. _this._rescalePostProcess.onApply = function (effect) {
  13259. effect._bindTexture("textureSampler", source);
  13260. };
  13261. var hostingScene = scene;
  13262. if (!hostingScene) {
  13263. hostingScene = _this.scenes[_this.scenes.length - 1];
  13264. }
  13265. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13266. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13267. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13268. _this.unBindFramebuffer(rtt);
  13269. _this._releaseTexture(rtt);
  13270. if (onComplete) {
  13271. onComplete();
  13272. }
  13273. });
  13274. };
  13275. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13276. if (compression === void 0) { compression = null; }
  13277. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13278. if (!texture) {
  13279. return;
  13280. }
  13281. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13282. var internalFormat = this._getInternalFormat(format);
  13283. var textureType = this._getWebGLTextureType(type);
  13284. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13285. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13286. if (!this._doNotHandleContextLost) {
  13287. texture._bufferView = data;
  13288. texture.format = format;
  13289. texture.type = type;
  13290. texture.invertY = invertY;
  13291. texture._compression = compression;
  13292. }
  13293. if (texture.width % 4 !== 0) {
  13294. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13295. }
  13296. if (compression && data) {
  13297. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13298. }
  13299. else {
  13300. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13301. }
  13302. if (texture.generateMipMaps) {
  13303. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13304. }
  13305. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13306. // this.resetTextureCache();
  13307. texture.isReady = true;
  13308. };
  13309. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13310. if (compression === void 0) { compression = null; }
  13311. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13312. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13313. texture.baseWidth = width;
  13314. texture.baseHeight = height;
  13315. texture.width = width;
  13316. texture.height = height;
  13317. texture.format = format;
  13318. texture.generateMipMaps = generateMipMaps;
  13319. texture.samplingMode = samplingMode;
  13320. texture.invertY = invertY;
  13321. texture._compression = compression;
  13322. texture.type = type;
  13323. if (!this._doNotHandleContextLost) {
  13324. texture._bufferView = data;
  13325. }
  13326. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13327. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13328. // Filters
  13329. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13330. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13332. if (generateMipMaps) {
  13333. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13334. }
  13335. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13336. this._internalTexturesCache.push(texture);
  13337. return texture;
  13338. };
  13339. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13340. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13341. texture.baseWidth = width;
  13342. texture.baseHeight = height;
  13343. if (generateMipMaps) {
  13344. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13345. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13346. }
  13347. // this.resetTextureCache();
  13348. texture.width = width;
  13349. texture.height = height;
  13350. texture.isReady = false;
  13351. texture.generateMipMaps = generateMipMaps;
  13352. texture.samplingMode = samplingMode;
  13353. this.updateTextureSamplingMode(samplingMode, texture);
  13354. this._internalTexturesCache.push(texture);
  13355. return texture;
  13356. };
  13357. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13358. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13359. if (texture.isCube) {
  13360. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13361. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13362. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13363. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13364. }
  13365. else if (texture.is3D) {
  13366. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13367. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13368. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13369. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13370. }
  13371. else {
  13372. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13373. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13374. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13375. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13376. }
  13377. texture.samplingMode = samplingMode;
  13378. };
  13379. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13380. if (premulAlpha === void 0) { premulAlpha = false; }
  13381. if (!texture) {
  13382. return;
  13383. }
  13384. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13385. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13386. if (premulAlpha) {
  13387. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13388. }
  13389. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13390. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13391. if (texture.generateMipMaps) {
  13392. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13393. }
  13394. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13395. if (premulAlpha) {
  13396. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13397. }
  13398. texture.isReady = true;
  13399. };
  13400. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13401. if (!texture || texture._isDisabled) {
  13402. return;
  13403. }
  13404. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13405. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13406. try {
  13407. // Testing video texture support
  13408. if (this._videoTextureSupported === undefined) {
  13409. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13410. if (this._gl.getError() !== 0) {
  13411. this._videoTextureSupported = false;
  13412. }
  13413. else {
  13414. this._videoTextureSupported = true;
  13415. }
  13416. }
  13417. // Copy video through the current working canvas if video texture is not supported
  13418. if (!this._videoTextureSupported) {
  13419. if (!texture._workingCanvas) {
  13420. texture._workingCanvas = document.createElement("canvas");
  13421. var context = texture._workingCanvas.getContext("2d");
  13422. if (!context) {
  13423. throw new Error("Unable to get 2d context");
  13424. }
  13425. texture._workingContext = context;
  13426. texture._workingCanvas.width = texture.width;
  13427. texture._workingCanvas.height = texture.height;
  13428. }
  13429. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13430. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13431. }
  13432. else {
  13433. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13434. }
  13435. if (texture.generateMipMaps) {
  13436. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13437. }
  13438. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13439. // this.resetTextureCache();
  13440. texture.isReady = true;
  13441. }
  13442. catch (ex) {
  13443. // Something unexpected
  13444. // Let's disable the texture
  13445. texture._isDisabled = true;
  13446. }
  13447. };
  13448. /**
  13449. * Updates a depth texture Comparison Mode and Function.
  13450. * If the comparison Function is equal to 0, the mode will be set to none.
  13451. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13452. * @param texture The texture to set the comparison function for
  13453. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13454. */
  13455. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13456. if (this.webGLVersion === 1) {
  13457. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13458. return;
  13459. }
  13460. var gl = this._gl;
  13461. if (texture.isCube) {
  13462. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13463. if (comparisonFunction === 0) {
  13464. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13465. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13466. }
  13467. else {
  13468. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13469. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13470. }
  13471. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13472. }
  13473. else {
  13474. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13475. if (comparisonFunction === 0) {
  13476. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13477. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13478. }
  13479. else {
  13480. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13481. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13482. }
  13483. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13484. }
  13485. texture._comparisonFunction = comparisonFunction;
  13486. };
  13487. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13488. var width = size.width || size;
  13489. var height = size.height || size;
  13490. internalTexture.baseWidth = width;
  13491. internalTexture.baseHeight = height;
  13492. internalTexture.width = width;
  13493. internalTexture.height = height;
  13494. internalTexture.isReady = true;
  13495. internalTexture.samples = 1;
  13496. internalTexture.generateMipMaps = false;
  13497. internalTexture._generateDepthBuffer = true;
  13498. internalTexture._generateStencilBuffer = generateStencil;
  13499. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13500. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13501. internalTexture._comparisonFunction = comparisonFunction;
  13502. var gl = this._gl;
  13503. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13504. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13505. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13506. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13507. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13508. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13509. if (comparisonFunction === 0) {
  13510. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13511. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13512. }
  13513. else {
  13514. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13515. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13516. }
  13517. };
  13518. /**
  13519. * Creates a depth stencil texture.
  13520. * This is only available in WebGL 2 or with the depth texture extension available.
  13521. * @param size The size of face edge in the texture.
  13522. * @param options The options defining the texture.
  13523. * @returns The texture
  13524. */
  13525. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13526. if (options.isCube) {
  13527. var width = size.width || size;
  13528. return this._createDepthStencilCubeTexture(width, options);
  13529. }
  13530. else {
  13531. return this._createDepthStencilTexture(size, options);
  13532. }
  13533. };
  13534. /**
  13535. * Creates a depth stencil texture.
  13536. * This is only available in WebGL 2 or with the depth texture extension available.
  13537. * @param size The size of face edge in the texture.
  13538. * @param options The options defining the texture.
  13539. * @returns The texture
  13540. */
  13541. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13542. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13543. if (!this._caps.depthTextureExtension) {
  13544. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13545. return internalTexture;
  13546. }
  13547. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13548. var gl = this._gl;
  13549. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13550. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13551. if (this.webGLVersion > 1) {
  13552. if (internalOptions.generateStencil) {
  13553. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13554. }
  13555. else {
  13556. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13557. }
  13558. }
  13559. else {
  13560. if (internalOptions.generateStencil) {
  13561. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13562. }
  13563. else {
  13564. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13565. }
  13566. }
  13567. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13568. return internalTexture;
  13569. };
  13570. /**
  13571. * Creates a depth stencil cube texture.
  13572. * This is only available in WebGL 2.
  13573. * @param size The size of face edge in the cube texture.
  13574. * @param options The options defining the cube texture.
  13575. * @returns The cube texture
  13576. */
  13577. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13578. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13579. internalTexture.isCube = true;
  13580. if (this.webGLVersion === 1) {
  13581. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13582. return internalTexture;
  13583. }
  13584. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13585. var gl = this._gl;
  13586. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13587. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13588. // Create the depth/stencil buffer
  13589. for (var face = 0; face < 6; face++) {
  13590. if (internalOptions.generateStencil) {
  13591. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13592. }
  13593. else {
  13594. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13595. }
  13596. }
  13597. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13598. return internalTexture;
  13599. };
  13600. /**
  13601. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13602. * @param renderTarget The render target to set the frame buffer for
  13603. */
  13604. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13605. // Create the framebuffer
  13606. var internalTexture = renderTarget.getInternalTexture();
  13607. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13608. return;
  13609. }
  13610. var gl = this._gl;
  13611. var depthStencilTexture = renderTarget.depthStencilTexture;
  13612. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13613. if (depthStencilTexture.isCube) {
  13614. if (depthStencilTexture._generateStencilBuffer) {
  13615. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13616. }
  13617. else {
  13618. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13619. }
  13620. }
  13621. else {
  13622. if (depthStencilTexture._generateStencilBuffer) {
  13623. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13624. }
  13625. else {
  13626. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13627. }
  13628. }
  13629. this.bindUnboundFramebuffer(null);
  13630. };
  13631. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13632. var fullOptions = new RenderTargetCreationOptions();
  13633. if (options !== undefined && typeof options === "object") {
  13634. fullOptions.generateMipMaps = options.generateMipMaps;
  13635. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13636. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13637. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13638. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13639. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13640. }
  13641. else {
  13642. fullOptions.generateMipMaps = options;
  13643. fullOptions.generateDepthBuffer = true;
  13644. fullOptions.generateStencilBuffer = false;
  13645. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13646. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13647. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13648. }
  13649. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13650. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13651. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13652. }
  13653. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13654. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13655. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13656. }
  13657. var gl = this._gl;
  13658. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13659. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13660. var width = size.width || size;
  13661. var height = size.height || size;
  13662. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13663. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13664. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13665. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13666. }
  13667. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13668. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13669. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13670. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13671. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13672. // Create the framebuffer
  13673. var framebuffer = gl.createFramebuffer();
  13674. this.bindUnboundFramebuffer(framebuffer);
  13675. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13676. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13677. if (fullOptions.generateMipMaps) {
  13678. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13679. }
  13680. // Unbind
  13681. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13682. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13683. this.bindUnboundFramebuffer(null);
  13684. texture._framebuffer = framebuffer;
  13685. texture.baseWidth = width;
  13686. texture.baseHeight = height;
  13687. texture.width = width;
  13688. texture.height = height;
  13689. texture.isReady = true;
  13690. texture.samples = 1;
  13691. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13692. texture.samplingMode = fullOptions.samplingMode;
  13693. texture.type = fullOptions.type;
  13694. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13695. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13696. // this.resetTextureCache();
  13697. this._internalTexturesCache.push(texture);
  13698. return texture;
  13699. };
  13700. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13701. var generateMipMaps = false;
  13702. var generateDepthBuffer = true;
  13703. var generateStencilBuffer = false;
  13704. var generateDepthTexture = false;
  13705. var textureCount = 1;
  13706. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13707. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13708. var types = [], samplingModes = [];
  13709. if (options !== undefined) {
  13710. generateMipMaps = options.generateMipMaps;
  13711. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13712. generateStencilBuffer = options.generateStencilBuffer;
  13713. generateDepthTexture = options.generateDepthTexture;
  13714. textureCount = options.textureCount || 1;
  13715. if (options.types) {
  13716. types = options.types;
  13717. }
  13718. if (options.samplingModes) {
  13719. samplingModes = options.samplingModes;
  13720. }
  13721. }
  13722. var gl = this._gl;
  13723. // Create the framebuffer
  13724. var framebuffer = gl.createFramebuffer();
  13725. this.bindUnboundFramebuffer(framebuffer);
  13726. var width = size.width || size;
  13727. var height = size.height || size;
  13728. var textures = [];
  13729. var attachments = [];
  13730. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13731. for (var i = 0; i < textureCount; i++) {
  13732. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13733. var type = types[i] || defaultType;
  13734. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13735. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13736. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13737. }
  13738. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13739. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13740. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13741. }
  13742. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13743. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13744. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13745. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13746. }
  13747. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13748. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13749. textures.push(texture);
  13750. attachments.push(attachment);
  13751. gl.activeTexture(gl["TEXTURE" + i]);
  13752. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13753. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13754. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13755. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13756. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13757. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13758. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13759. if (generateMipMaps) {
  13760. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13761. }
  13762. // Unbind
  13763. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13764. texture._framebuffer = framebuffer;
  13765. texture._depthStencilBuffer = depthStencilBuffer;
  13766. texture.baseWidth = width;
  13767. texture.baseHeight = height;
  13768. texture.width = width;
  13769. texture.height = height;
  13770. texture.isReady = true;
  13771. texture.samples = 1;
  13772. texture.generateMipMaps = generateMipMaps;
  13773. texture.samplingMode = samplingMode;
  13774. texture.type = type;
  13775. texture._generateDepthBuffer = generateDepthBuffer;
  13776. texture._generateStencilBuffer = generateStencilBuffer;
  13777. texture._attachments = attachments;
  13778. this._internalTexturesCache.push(texture);
  13779. }
  13780. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13781. // Depth texture
  13782. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13783. gl.activeTexture(gl.TEXTURE0);
  13784. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13785. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13786. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13787. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13788. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13789. 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);
  13790. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13791. depthTexture._framebuffer = framebuffer;
  13792. depthTexture.baseWidth = width;
  13793. depthTexture.baseHeight = height;
  13794. depthTexture.width = width;
  13795. depthTexture.height = height;
  13796. depthTexture.isReady = true;
  13797. depthTexture.samples = 1;
  13798. depthTexture.generateMipMaps = generateMipMaps;
  13799. depthTexture.samplingMode = gl.NEAREST;
  13800. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13801. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13802. textures.push(depthTexture);
  13803. this._internalTexturesCache.push(depthTexture);
  13804. }
  13805. gl.drawBuffers(attachments);
  13806. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13807. this.bindUnboundFramebuffer(null);
  13808. this.resetTextureCache();
  13809. return textures;
  13810. };
  13811. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13812. if (samples === void 0) { samples = 1; }
  13813. var depthStencilBuffer = null;
  13814. var gl = this._gl;
  13815. // Create the depth/stencil buffer
  13816. if (generateStencilBuffer) {
  13817. depthStencilBuffer = gl.createRenderbuffer();
  13818. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13819. if (samples > 1) {
  13820. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13821. }
  13822. else {
  13823. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13824. }
  13825. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13826. }
  13827. else if (generateDepthBuffer) {
  13828. depthStencilBuffer = gl.createRenderbuffer();
  13829. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13830. if (samples > 1) {
  13831. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13832. }
  13833. else {
  13834. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13835. }
  13836. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13837. }
  13838. return depthStencilBuffer;
  13839. };
  13840. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13841. if (this.webGLVersion < 2 || !texture) {
  13842. return 1;
  13843. }
  13844. if (texture.samples === samples) {
  13845. return samples;
  13846. }
  13847. var gl = this._gl;
  13848. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13849. // Dispose previous render buffers
  13850. if (texture._depthStencilBuffer) {
  13851. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13852. texture._depthStencilBuffer = null;
  13853. }
  13854. if (texture._MSAAFramebuffer) {
  13855. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13856. texture._MSAAFramebuffer = null;
  13857. }
  13858. if (texture._MSAARenderBuffer) {
  13859. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13860. texture._MSAARenderBuffer = null;
  13861. }
  13862. if (samples > 1) {
  13863. var framebuffer = gl.createFramebuffer();
  13864. if (!framebuffer) {
  13865. throw new Error("Unable to create multi sampled framebuffer");
  13866. }
  13867. texture._MSAAFramebuffer = framebuffer;
  13868. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13869. var colorRenderbuffer = gl.createRenderbuffer();
  13870. if (!colorRenderbuffer) {
  13871. throw new Error("Unable to create multi sampled framebuffer");
  13872. }
  13873. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13874. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13875. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13876. texture._MSAARenderBuffer = colorRenderbuffer;
  13877. }
  13878. else {
  13879. this.bindUnboundFramebuffer(texture._framebuffer);
  13880. }
  13881. texture.samples = samples;
  13882. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13883. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13884. this.bindUnboundFramebuffer(null);
  13885. return samples;
  13886. };
  13887. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13888. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13889. return 1;
  13890. }
  13891. if (textures[0].samples === samples) {
  13892. return samples;
  13893. }
  13894. var gl = this._gl;
  13895. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13896. // Dispose previous render buffers
  13897. if (textures[0]._depthStencilBuffer) {
  13898. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13899. textures[0]._depthStencilBuffer = null;
  13900. }
  13901. if (textures[0]._MSAAFramebuffer) {
  13902. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13903. textures[0]._MSAAFramebuffer = null;
  13904. }
  13905. for (var i = 0; i < textures.length; i++) {
  13906. if (textures[i]._MSAARenderBuffer) {
  13907. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13908. textures[i]._MSAARenderBuffer = null;
  13909. }
  13910. }
  13911. if (samples > 1) {
  13912. var framebuffer = gl.createFramebuffer();
  13913. if (!framebuffer) {
  13914. throw new Error("Unable to create multi sampled framebuffer");
  13915. }
  13916. this.bindUnboundFramebuffer(framebuffer);
  13917. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13918. var attachments = [];
  13919. for (var i = 0; i < textures.length; i++) {
  13920. var texture = textures[i];
  13921. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13922. var colorRenderbuffer = gl.createRenderbuffer();
  13923. if (!colorRenderbuffer) {
  13924. throw new Error("Unable to create multi sampled framebuffer");
  13925. }
  13926. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13927. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13928. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13929. texture._MSAAFramebuffer = framebuffer;
  13930. texture._MSAARenderBuffer = colorRenderbuffer;
  13931. texture.samples = samples;
  13932. texture._depthStencilBuffer = depthStencilBuffer;
  13933. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13934. attachments.push(attachment);
  13935. }
  13936. gl.drawBuffers(attachments);
  13937. }
  13938. else {
  13939. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13940. }
  13941. this.bindUnboundFramebuffer(null);
  13942. return samples;
  13943. };
  13944. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13945. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13946. };
  13947. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13948. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13949. };
  13950. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13951. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13952. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13953. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13954. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13955. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13956. }
  13957. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13958. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13959. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13960. }
  13961. var gl = this._gl;
  13962. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13963. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13964. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13965. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13966. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13967. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13968. }
  13969. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13970. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13971. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13972. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13973. for (var face = 0; face < 6; face++) {
  13974. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13975. }
  13976. // Create the framebuffer
  13977. var framebuffer = gl.createFramebuffer();
  13978. this.bindUnboundFramebuffer(framebuffer);
  13979. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13980. // MipMaps
  13981. if (fullOptions.generateMipMaps) {
  13982. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13983. }
  13984. // Unbind
  13985. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13986. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13987. this.bindUnboundFramebuffer(null);
  13988. texture._framebuffer = framebuffer;
  13989. texture.width = size;
  13990. texture.height = size;
  13991. texture.isReady = true;
  13992. texture.isCube = true;
  13993. texture.samples = 1;
  13994. texture.generateMipMaps = fullOptions.generateMipMaps;
  13995. texture.samplingMode = fullOptions.samplingMode;
  13996. texture.type = fullOptions.type;
  13997. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13998. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13999. this._internalTexturesCache.push(texture);
  14000. return texture;
  14001. };
  14002. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  14003. var _this = this;
  14004. if (onLoad === void 0) { onLoad = null; }
  14005. if (onError === void 0) { onError = null; }
  14006. if (forcedExtension === void 0) { forcedExtension = null; }
  14007. var callback = function (loadData) {
  14008. if (!loadData) {
  14009. if (onLoad) {
  14010. onLoad(null);
  14011. }
  14012. return;
  14013. }
  14014. var texture = loadData.texture;
  14015. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14016. texture._lodGenerationScale = scale;
  14017. texture._lodGenerationOffset = offset;
  14018. if (_this._caps.textureLOD) {
  14019. // Do not add extra process if texture lod is supported.
  14020. if (onLoad) {
  14021. onLoad(texture);
  14022. }
  14023. return;
  14024. }
  14025. var mipSlices = 3;
  14026. var gl = _this._gl;
  14027. var width = loadData.width;
  14028. if (!width) {
  14029. return;
  14030. }
  14031. var textures = [];
  14032. for (var i = 0; i < mipSlices; i++) {
  14033. //compute LOD from even spacing in smoothness (matching shader calculation)
  14034. var smoothness = i / (mipSlices - 1);
  14035. var roughness = 1 - smoothness;
  14036. var minLODIndex = offset; // roughness = 0
  14037. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14038. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14039. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14040. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14041. glTextureFromLod.isCube = true;
  14042. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14043. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14044. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14045. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14046. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14047. if (loadData.isDDS) {
  14048. var info = loadData.info;
  14049. var data = loadData.data;
  14050. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14051. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14052. }
  14053. else {
  14054. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14055. }
  14056. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14057. // Wrap in a base texture for easy binding.
  14058. var lodTexture = new BABYLON.BaseTexture(scene);
  14059. lodTexture.isCube = true;
  14060. lodTexture._texture = glTextureFromLod;
  14061. glTextureFromLod.isReady = true;
  14062. textures.push(lodTexture);
  14063. }
  14064. texture._lodTextureHigh = textures[2];
  14065. texture._lodTextureMid = textures[1];
  14066. texture._lodTextureLow = textures[0];
  14067. if (onLoad) {
  14068. onLoad(texture);
  14069. }
  14070. };
  14071. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14072. };
  14073. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14074. var _this = this;
  14075. if (onLoad === void 0) { onLoad = null; }
  14076. if (onError === void 0) { onError = null; }
  14077. if (forcedExtension === void 0) { forcedExtension = null; }
  14078. var gl = this._gl;
  14079. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14080. texture.isCube = true;
  14081. texture.url = rootUrl;
  14082. texture.generateMipMaps = !noMipmap;
  14083. if (!this._doNotHandleContextLost) {
  14084. texture._extension = forcedExtension;
  14085. texture._files = files;
  14086. }
  14087. var isKTX = false;
  14088. var isDDS = false;
  14089. var lastDot = rootUrl.lastIndexOf('.');
  14090. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14091. if (this._textureFormatInUse) {
  14092. extension = this._textureFormatInUse;
  14093. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14094. isKTX = true;
  14095. }
  14096. else {
  14097. isDDS = (extension === ".dds");
  14098. }
  14099. var onerror = function (request, exception) {
  14100. if (onError && request) {
  14101. onError(request.status + " " + request.statusText, exception);
  14102. }
  14103. };
  14104. if (isKTX) {
  14105. this._loadFile(rootUrl, function (data) {
  14106. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14107. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14108. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14109. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14110. ktx.uploadLevels(_this._gl, !noMipmap);
  14111. _this.setCubeMapTextureParams(gl, loadMipmap);
  14112. texture.width = ktx.pixelWidth;
  14113. texture.height = ktx.pixelHeight;
  14114. texture.isReady = true;
  14115. }, undefined, undefined, true, onerror);
  14116. }
  14117. else if (isDDS) {
  14118. if (files && files.length === 6) {
  14119. this._cascadeLoadFiles(scene, function (imgs) {
  14120. var info;
  14121. var loadMipmap = false;
  14122. var width = 0;
  14123. for (var index = 0; index < imgs.length; index++) {
  14124. var data = imgs[index];
  14125. info = BABYLON.DDSTools.GetDDSInfo(data);
  14126. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14127. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14128. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14129. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14130. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14131. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14132. }
  14133. texture.width = info.width;
  14134. texture.height = info.height;
  14135. texture.type = info.textureType;
  14136. width = info.width;
  14137. }
  14138. _this.setCubeMapTextureParams(gl, loadMipmap);
  14139. texture.isReady = true;
  14140. if (onLoad) {
  14141. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14142. }
  14143. }, files, onError);
  14144. }
  14145. else {
  14146. this._loadFile(rootUrl, function (data) {
  14147. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14148. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14149. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14150. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14151. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14152. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14153. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14154. }
  14155. _this.setCubeMapTextureParams(gl, loadMipmap);
  14156. texture.width = info.width;
  14157. texture.height = info.height;
  14158. texture.isReady = true;
  14159. texture.type = info.textureType;
  14160. if (onLoad) {
  14161. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14162. }
  14163. }, undefined, undefined, true, onerror);
  14164. }
  14165. }
  14166. else {
  14167. if (!files) {
  14168. throw new Error("Cannot load cubemap because files were not defined");
  14169. }
  14170. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14171. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14172. var height = width;
  14173. _this._prepareWorkingCanvas();
  14174. if (!_this._workingCanvas || !_this._workingContext) {
  14175. return;
  14176. }
  14177. _this._workingCanvas.width = width;
  14178. _this._workingCanvas.height = height;
  14179. var faces = [
  14180. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14181. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14182. ];
  14183. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14184. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14185. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14186. for (var index = 0; index < faces.length; index++) {
  14187. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14188. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14189. }
  14190. if (!noMipmap) {
  14191. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14192. }
  14193. _this.setCubeMapTextureParams(gl, !noMipmap);
  14194. texture.width = width;
  14195. texture.height = height;
  14196. texture.isReady = true;
  14197. if (format) {
  14198. texture.format = format;
  14199. }
  14200. texture.onLoadedObservable.notifyObservers(texture);
  14201. texture.onLoadedObservable.clear();
  14202. if (onLoad) {
  14203. onLoad();
  14204. }
  14205. }, files, onError);
  14206. }
  14207. this._internalTexturesCache.push(texture);
  14208. return texture;
  14209. };
  14210. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14211. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14212. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14213. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14214. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14215. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14216. // this.resetTextureCache();
  14217. };
  14218. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14219. if (compression === void 0) { compression = null; }
  14220. if (level === void 0) { level = 0; }
  14221. texture._bufferViewArray = data;
  14222. texture.format = format;
  14223. texture.type = type;
  14224. texture.invertY = invertY;
  14225. texture._compression = compression;
  14226. var gl = this._gl;
  14227. var textureType = this._getWebGLTextureType(type);
  14228. var internalFormat = this._getInternalFormat(format);
  14229. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14230. var needConversion = false;
  14231. if (internalFormat === gl.RGB) {
  14232. internalFormat = gl.RGBA;
  14233. needConversion = true;
  14234. }
  14235. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14236. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14237. if (texture.width % 4 !== 0) {
  14238. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14239. }
  14240. // Data are known to be in +X +Y +Z -X -Y -Z
  14241. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14242. var faceData = data[faceIndex];
  14243. if (compression) {
  14244. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14245. }
  14246. else {
  14247. if (needConversion) {
  14248. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14249. }
  14250. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14251. }
  14252. }
  14253. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14254. if (isPot && texture.generateMipMaps && level === 0) {
  14255. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14256. }
  14257. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14258. // this.resetTextureCache();
  14259. texture.isReady = true;
  14260. };
  14261. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14262. if (compression === void 0) { compression = null; }
  14263. var gl = this._gl;
  14264. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14265. texture.isCube = true;
  14266. texture.generateMipMaps = generateMipMaps;
  14267. texture.format = format;
  14268. texture.type = type;
  14269. if (!this._doNotHandleContextLost) {
  14270. texture._bufferViewArray = data;
  14271. }
  14272. var textureType = this._getWebGLTextureType(type);
  14273. var internalFormat = this._getInternalFormat(format);
  14274. if (internalFormat === gl.RGB) {
  14275. internalFormat = gl.RGBA;
  14276. }
  14277. var width = size;
  14278. var height = width;
  14279. texture.width = width;
  14280. texture.height = height;
  14281. // Double check on POT to generate Mips.
  14282. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14283. if (!isPot) {
  14284. generateMipMaps = false;
  14285. }
  14286. // Upload data if needed. The texture won't be ready until then.
  14287. if (data) {
  14288. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14289. }
  14290. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14291. // Filters
  14292. if (data && generateMipMaps) {
  14293. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14294. }
  14295. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14296. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14298. }
  14299. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14300. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14301. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14302. }
  14303. else {
  14304. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14305. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14306. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14307. }
  14308. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14309. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14310. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14311. return texture;
  14312. };
  14313. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14314. var _this = this;
  14315. if (onLoad === void 0) { onLoad = null; }
  14316. if (onError === void 0) { onError = null; }
  14317. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14318. if (invertY === void 0) { invertY = false; }
  14319. var gl = this._gl;
  14320. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14321. scene._addPendingData(texture);
  14322. texture.url = url;
  14323. this._internalTexturesCache.push(texture);
  14324. var onerror = function (request, exception) {
  14325. scene._removePendingData(texture);
  14326. if (onError && request) {
  14327. onError(request.status + " " + request.statusText, exception);
  14328. }
  14329. };
  14330. var internalCallback = function (data) {
  14331. var width = texture.width;
  14332. var faceDataArrays = callback(data);
  14333. if (!faceDataArrays) {
  14334. return;
  14335. }
  14336. if (mipmmapGenerator) {
  14337. var textureType = _this._getWebGLTextureType(type);
  14338. var internalFormat = _this._getInternalFormat(format);
  14339. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14340. var needConversion = false;
  14341. if (internalFormat === gl.RGB) {
  14342. internalFormat = gl.RGBA;
  14343. needConversion = true;
  14344. }
  14345. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14346. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14347. var mipData = mipmmapGenerator(faceDataArrays);
  14348. for (var level = 0; level < mipData.length; level++) {
  14349. var mipSize = width >> level;
  14350. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14351. var mipFaceData = mipData[level][faceIndex];
  14352. if (needConversion) {
  14353. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14354. }
  14355. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14356. }
  14357. }
  14358. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14359. }
  14360. else {
  14361. texture.generateMipMaps = !noMipmap;
  14362. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14363. }
  14364. texture.isReady = true;
  14365. // this.resetTextureCache();
  14366. scene._removePendingData(texture);
  14367. if (onLoad) {
  14368. onLoad();
  14369. }
  14370. };
  14371. this._loadFile(url, function (data) {
  14372. internalCallback(data);
  14373. }, undefined, scene.database, true, onerror);
  14374. return texture;
  14375. };
  14376. ;
  14377. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14378. if (compression === void 0) { compression = null; }
  14379. var internalFormat = this._getInternalFormat(format);
  14380. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14381. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14382. if (!this._doNotHandleContextLost) {
  14383. texture._bufferView = data;
  14384. texture.format = format;
  14385. texture.invertY = invertY;
  14386. texture._compression = compression;
  14387. }
  14388. if (texture.width % 4 !== 0) {
  14389. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14390. }
  14391. if (compression && data) {
  14392. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14393. }
  14394. else {
  14395. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14396. }
  14397. if (texture.generateMipMaps) {
  14398. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14399. }
  14400. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14401. // this.resetTextureCache();
  14402. texture.isReady = true;
  14403. };
  14404. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14405. if (compression === void 0) { compression = null; }
  14406. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14407. texture.baseWidth = width;
  14408. texture.baseHeight = height;
  14409. texture.baseDepth = depth;
  14410. texture.width = width;
  14411. texture.height = height;
  14412. texture.depth = depth;
  14413. texture.format = format;
  14414. texture.generateMipMaps = generateMipMaps;
  14415. texture.samplingMode = samplingMode;
  14416. texture.is3D = true;
  14417. if (!this._doNotHandleContextLost) {
  14418. texture._bufferView = data;
  14419. }
  14420. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14421. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14422. // Filters
  14423. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14424. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14425. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14426. if (generateMipMaps) {
  14427. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14428. }
  14429. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14430. this._internalTexturesCache.push(texture);
  14431. return texture;
  14432. };
  14433. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14434. var gl = this._gl;
  14435. if (!gl) {
  14436. return;
  14437. }
  14438. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14439. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14440. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14441. if (!noMipmap && !isCompressed) {
  14442. gl.generateMipmap(gl.TEXTURE_2D);
  14443. }
  14444. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14445. // this.resetTextureCache();
  14446. if (scene) {
  14447. scene._removePendingData(texture);
  14448. }
  14449. texture.onLoadedObservable.notifyObservers(texture);
  14450. texture.onLoadedObservable.clear();
  14451. };
  14452. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14453. var _this = this;
  14454. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14455. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14456. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14457. var gl = this._gl;
  14458. if (!gl) {
  14459. return;
  14460. }
  14461. if (!texture._webGLTexture) {
  14462. // this.resetTextureCache();
  14463. if (scene) {
  14464. scene._removePendingData(texture);
  14465. }
  14466. return;
  14467. }
  14468. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14469. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14470. texture.baseWidth = width;
  14471. texture.baseHeight = height;
  14472. texture.width = potWidth;
  14473. texture.height = potHeight;
  14474. texture.isReady = true;
  14475. if (processFunction(potWidth, potHeight, function () {
  14476. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14477. })) {
  14478. // Returning as texture needs extra async steps
  14479. return;
  14480. }
  14481. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14482. };
  14483. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14484. // Create new RGBA data container.
  14485. var rgbaData;
  14486. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14487. rgbaData = new Float32Array(width * height * 4);
  14488. }
  14489. else {
  14490. rgbaData = new Uint32Array(width * height * 4);
  14491. }
  14492. // Convert each pixel.
  14493. for (var x = 0; x < width; x++) {
  14494. for (var y = 0; y < height; y++) {
  14495. var index = (y * width + x) * 3;
  14496. var newIndex = (y * width + x) * 4;
  14497. // Map Old Value to new value.
  14498. rgbaData[newIndex + 0] = rgbData[index + 0];
  14499. rgbaData[newIndex + 1] = rgbData[index + 1];
  14500. rgbaData[newIndex + 2] = rgbData[index + 2];
  14501. // Add fully opaque alpha channel.
  14502. rgbaData[newIndex + 3] = 1;
  14503. }
  14504. }
  14505. return rgbaData;
  14506. };
  14507. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14508. var gl = this._gl;
  14509. if (texture._framebuffer) {
  14510. gl.deleteFramebuffer(texture._framebuffer);
  14511. texture._framebuffer = null;
  14512. }
  14513. if (texture._depthStencilBuffer) {
  14514. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14515. texture._depthStencilBuffer = null;
  14516. }
  14517. if (texture._MSAAFramebuffer) {
  14518. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14519. texture._MSAAFramebuffer = null;
  14520. }
  14521. if (texture._MSAARenderBuffer) {
  14522. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14523. texture._MSAARenderBuffer = null;
  14524. }
  14525. };
  14526. Engine.prototype._releaseTexture = function (texture) {
  14527. var gl = this._gl;
  14528. this._releaseFramebufferObjects(texture);
  14529. gl.deleteTexture(texture._webGLTexture);
  14530. // Unbind channels
  14531. this.unbindAllTextures();
  14532. var index = this._internalTexturesCache.indexOf(texture);
  14533. if (index !== -1) {
  14534. this._internalTexturesCache.splice(index, 1);
  14535. }
  14536. // Integrated fixed lod samplers.
  14537. if (texture._lodTextureHigh) {
  14538. texture._lodTextureHigh.dispose();
  14539. }
  14540. if (texture._lodTextureMid) {
  14541. texture._lodTextureMid.dispose();
  14542. }
  14543. if (texture._lodTextureLow) {
  14544. texture._lodTextureLow.dispose();
  14545. }
  14546. // Set output texture of post process to null if the texture has been released/disposed
  14547. this.scenes.forEach(function (scene) {
  14548. scene.postProcesses.forEach(function (postProcess) {
  14549. if (postProcess._outputTexture == texture) {
  14550. postProcess._outputTexture = null;
  14551. }
  14552. });
  14553. scene.cameras.forEach(function (camera) {
  14554. camera._postProcesses.forEach(function (postProcess) {
  14555. if (postProcess) {
  14556. if (postProcess._outputTexture == texture) {
  14557. postProcess._outputTexture = null;
  14558. }
  14559. }
  14560. });
  14561. });
  14562. });
  14563. };
  14564. Engine.prototype.setProgram = function (program) {
  14565. if (this._currentProgram !== program) {
  14566. this._gl.useProgram(program);
  14567. this._currentProgram = program;
  14568. }
  14569. };
  14570. Engine.prototype.bindSamplers = function (effect) {
  14571. this.setProgram(effect.getProgram());
  14572. var samplers = effect.getSamplers();
  14573. for (var index = 0; index < samplers.length; index++) {
  14574. var uniform = effect.getUniform(samplers[index]);
  14575. if (uniform) {
  14576. this._boundUniforms[index] = uniform;
  14577. }
  14578. }
  14579. this._currentEffect = null;
  14580. };
  14581. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14582. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14583. return;
  14584. }
  14585. // Remove
  14586. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14587. // Bind last to it
  14588. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14589. // Bind to dummy
  14590. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14591. };
  14592. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14593. if (!internalTexture) {
  14594. return -1;
  14595. }
  14596. internalTexture._initialSlot = channel;
  14597. if (this.disableTextureBindingOptimization) {
  14598. if (channel !== internalTexture._designatedSlot) {
  14599. this._textureCollisions.addCount(1, false);
  14600. }
  14601. }
  14602. else {
  14603. if (channel !== internalTexture._designatedSlot) {
  14604. if (internalTexture._designatedSlot > -1) {
  14605. return internalTexture._designatedSlot;
  14606. }
  14607. else {
  14608. // No slot for this texture, let's pick a new one (if we find a free slot)
  14609. if (this._nextFreeTextureSlots.length) {
  14610. return this._nextFreeTextureSlots[0];
  14611. }
  14612. // We need to recycle the oldest bound texture, sorry.
  14613. this._textureCollisions.addCount(1, false);
  14614. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14615. }
  14616. }
  14617. }
  14618. return channel;
  14619. };
  14620. Engine.prototype._linkTrackers = function (previous, next) {
  14621. previous.next = next;
  14622. next.previous = previous;
  14623. };
  14624. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14625. var currentSlot = internalTexture._designatedSlot;
  14626. if (currentSlot === -1) {
  14627. return -1;
  14628. }
  14629. internalTexture._designatedSlot = -1;
  14630. if (this.disableTextureBindingOptimization) {
  14631. return -1;
  14632. }
  14633. // Remove from bound list
  14634. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14635. // Free the slot
  14636. this._boundTexturesCache[currentSlot] = null;
  14637. this._nextFreeTextureSlots.push(currentSlot);
  14638. return currentSlot;
  14639. };
  14640. Engine.prototype._activateCurrentTexture = function () {
  14641. if (this._currentTextureChannel !== this._activeChannel) {
  14642. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14643. this._currentTextureChannel = this._activeChannel;
  14644. }
  14645. };
  14646. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14647. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14648. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14649. this._activeChannel = texture._designatedSlot;
  14650. }
  14651. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14652. var isTextureForRendering = texture && texture._initialSlot > -1;
  14653. if (currentTextureBound !== texture) {
  14654. if (currentTextureBound) {
  14655. this._removeDesignatedSlot(currentTextureBound);
  14656. }
  14657. this._activateCurrentTexture();
  14658. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14659. this._boundTexturesCache[this._activeChannel] = texture;
  14660. if (texture) {
  14661. if (!this.disableTextureBindingOptimization) {
  14662. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14663. if (slotIndex > -1) {
  14664. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14665. }
  14666. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14667. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14668. }
  14669. texture._designatedSlot = this._activeChannel;
  14670. }
  14671. }
  14672. else if (forTextureDataUpdate) {
  14673. this._activateCurrentTexture();
  14674. }
  14675. if (isTextureForRendering && !forTextureDataUpdate) {
  14676. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14677. }
  14678. };
  14679. Engine.prototype._bindTexture = function (channel, texture) {
  14680. if (channel < 0) {
  14681. return;
  14682. }
  14683. if (texture) {
  14684. channel = this._getCorrectTextureChannel(channel, texture);
  14685. }
  14686. this._activeChannel = channel;
  14687. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14688. };
  14689. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14690. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14691. };
  14692. /**
  14693. * Binds the output of the passed in post process to the texture channel specified
  14694. * @param channel The channel the texture should be bound to
  14695. * @param postProcess The post process which's output should be bound
  14696. */
  14697. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14698. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14699. };
  14700. Engine.prototype.unbindAllTextures = function () {
  14701. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14702. this._activeChannel = channel;
  14703. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14704. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14705. if (this.webGLVersion > 1) {
  14706. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14707. }
  14708. }
  14709. };
  14710. /**
  14711. * Sets a texture to the according uniform.
  14712. * @param channel The texture channel
  14713. * @param uniform The uniform to set
  14714. * @param texture The texture to apply
  14715. */
  14716. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14717. if (channel < 0) {
  14718. return;
  14719. }
  14720. if (uniform) {
  14721. this._boundUniforms[channel] = uniform;
  14722. }
  14723. this._setTexture(channel, texture);
  14724. };
  14725. /**
  14726. * Sets a depth stencil texture from a render target to the according uniform.
  14727. * @param channel The texture channel
  14728. * @param uniform The uniform to set
  14729. * @param texture The render target texture containing the depth stencil texture to apply
  14730. */
  14731. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14732. if (channel < 0) {
  14733. return;
  14734. }
  14735. if (uniform) {
  14736. this._boundUniforms[channel] = uniform;
  14737. }
  14738. if (!texture || !texture.depthStencilTexture) {
  14739. this._setTexture(channel, null);
  14740. }
  14741. else {
  14742. this._setTexture(channel, texture, false, true);
  14743. }
  14744. };
  14745. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14746. var uniform = this._boundUniforms[sourceSlot];
  14747. if (uniform._currentState === destination) {
  14748. return;
  14749. }
  14750. this._gl.uniform1i(uniform, destination);
  14751. uniform._currentState = destination;
  14752. };
  14753. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14754. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14755. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14756. // Not ready?
  14757. if (!texture) {
  14758. if (this._boundTexturesCache[channel] != null) {
  14759. this._activeChannel = channel;
  14760. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14761. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14762. if (this.webGLVersion > 1) {
  14763. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14764. }
  14765. }
  14766. return false;
  14767. }
  14768. // Video
  14769. if (texture.video) {
  14770. this._activeChannel = channel;
  14771. texture.update();
  14772. }
  14773. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14774. texture.delayLoad();
  14775. return false;
  14776. }
  14777. var internalTexture;
  14778. if (depthStencilTexture) {
  14779. internalTexture = texture.depthStencilTexture;
  14780. }
  14781. else if (texture.isReady()) {
  14782. internalTexture = texture.getInternalTexture();
  14783. }
  14784. else if (texture.isCube) {
  14785. internalTexture = this.emptyCubeTexture;
  14786. }
  14787. else if (texture.is3D) {
  14788. internalTexture = this.emptyTexture3D;
  14789. }
  14790. else {
  14791. internalTexture = this.emptyTexture;
  14792. }
  14793. if (!isPartOfTextureArray) {
  14794. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14795. }
  14796. if (this._boundTexturesCache[channel] === internalTexture) {
  14797. this._moveBoundTextureOnTop(internalTexture);
  14798. if (!isPartOfTextureArray) {
  14799. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14800. }
  14801. return false;
  14802. }
  14803. this._activeChannel = channel;
  14804. if (internalTexture && internalTexture.is3D) {
  14805. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14806. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14807. internalTexture._cachedWrapU = texture.wrapU;
  14808. switch (texture.wrapU) {
  14809. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14810. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14811. break;
  14812. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14813. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14814. break;
  14815. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14816. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14817. break;
  14818. }
  14819. }
  14820. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14821. internalTexture._cachedWrapV = texture.wrapV;
  14822. switch (texture.wrapV) {
  14823. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14824. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14825. break;
  14826. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14827. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14828. break;
  14829. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14830. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14831. break;
  14832. }
  14833. }
  14834. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14835. internalTexture._cachedWrapR = texture.wrapR;
  14836. switch (texture.wrapR) {
  14837. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14838. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14839. break;
  14840. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14841. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14842. break;
  14843. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14844. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14845. break;
  14846. }
  14847. }
  14848. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14849. }
  14850. else if (internalTexture && internalTexture.isCube) {
  14851. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14852. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14853. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14854. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14855. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14856. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14857. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14858. }
  14859. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14860. }
  14861. else {
  14862. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14863. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14864. internalTexture._cachedWrapU = texture.wrapU;
  14865. switch (texture.wrapU) {
  14866. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14867. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14868. break;
  14869. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14870. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14871. break;
  14872. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14873. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14874. break;
  14875. }
  14876. }
  14877. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14878. internalTexture._cachedWrapV = texture.wrapV;
  14879. switch (texture.wrapV) {
  14880. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14881. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14882. break;
  14883. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14884. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14885. break;
  14886. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14887. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14888. break;
  14889. }
  14890. }
  14891. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14892. }
  14893. return true;
  14894. };
  14895. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14896. if (channel < 0 || !uniform) {
  14897. return;
  14898. }
  14899. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14900. this._textureUnits = new Int32Array(textures.length);
  14901. }
  14902. for (var i = 0; i < textures.length; i++) {
  14903. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14904. }
  14905. this._gl.uniform1iv(uniform, this._textureUnits);
  14906. for (var index = 0; index < textures.length; index++) {
  14907. this._setTexture(this._textureUnits[index], textures[index], true);
  14908. }
  14909. };
  14910. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14911. var internalTexture = texture.getInternalTexture();
  14912. if (!internalTexture) {
  14913. return;
  14914. }
  14915. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14916. var value = texture.anisotropicFilteringLevel;
  14917. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14918. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14919. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14920. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14921. }
  14922. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14923. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14924. internalTexture._cachedAnisotropicFilteringLevel = value;
  14925. }
  14926. };
  14927. Engine.prototype.readPixels = function (x, y, width, height) {
  14928. var data = new Uint8Array(height * width * 4);
  14929. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14930. return data;
  14931. };
  14932. /**
  14933. * Add an externaly attached data from its key.
  14934. * This method call will fail and return false, if such key already exists.
  14935. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14936. * @param key the unique key that identifies the data
  14937. * @param data the data object to associate to the key for this Engine instance
  14938. * @return true if no such key were already present and the data was added successfully, false otherwise
  14939. */
  14940. Engine.prototype.addExternalData = function (key, data) {
  14941. if (!this._externalData) {
  14942. this._externalData = new BABYLON.StringDictionary();
  14943. }
  14944. return this._externalData.add(key, data);
  14945. };
  14946. /**
  14947. * Get an externaly attached data from its key
  14948. * @param key the unique key that identifies the data
  14949. * @return the associated data, if present (can be null), or undefined if not present
  14950. */
  14951. Engine.prototype.getExternalData = function (key) {
  14952. if (!this._externalData) {
  14953. this._externalData = new BABYLON.StringDictionary();
  14954. }
  14955. return this._externalData.get(key);
  14956. };
  14957. /**
  14958. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14959. * @param key the unique key that identifies the data
  14960. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14961. * @return the associated data, can be null if the factory returned null.
  14962. */
  14963. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14964. if (!this._externalData) {
  14965. this._externalData = new BABYLON.StringDictionary();
  14966. }
  14967. return this._externalData.getOrAddWithFactory(key, factory);
  14968. };
  14969. /**
  14970. * Remove an externaly attached data from the Engine instance
  14971. * @param key the unique key that identifies the data
  14972. * @return true if the data was successfully removed, false if it doesn't exist
  14973. */
  14974. Engine.prototype.removeExternalData = function (key) {
  14975. if (!this._externalData) {
  14976. this._externalData = new BABYLON.StringDictionary();
  14977. }
  14978. return this._externalData.remove(key);
  14979. };
  14980. Engine.prototype.unbindAllAttributes = function () {
  14981. if (this._mustWipeVertexAttributes) {
  14982. this._mustWipeVertexAttributes = false;
  14983. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14984. this._gl.disableVertexAttribArray(i);
  14985. this._vertexAttribArraysEnabled[i] = false;
  14986. this._currentBufferPointers[i].active = false;
  14987. }
  14988. return;
  14989. }
  14990. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14991. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14992. continue;
  14993. }
  14994. this._gl.disableVertexAttribArray(i);
  14995. this._vertexAttribArraysEnabled[i] = false;
  14996. this._currentBufferPointers[i].active = false;
  14997. }
  14998. };
  14999. Engine.prototype.releaseEffects = function () {
  15000. for (var name in this._compiledEffects) {
  15001. this._deleteProgram(this._compiledEffects[name]._program);
  15002. }
  15003. this._compiledEffects = {};
  15004. };
  15005. // Dispose
  15006. Engine.prototype.dispose = function () {
  15007. this.hideLoadingUI();
  15008. this.stopRenderLoop();
  15009. // Release postProcesses
  15010. while (this.postProcesses.length) {
  15011. this.postProcesses[0].dispose();
  15012. }
  15013. // Empty texture
  15014. if (this._emptyTexture) {
  15015. this._releaseTexture(this._emptyTexture);
  15016. this._emptyTexture = null;
  15017. }
  15018. if (this._emptyCubeTexture) {
  15019. this._releaseTexture(this._emptyCubeTexture);
  15020. this._emptyCubeTexture = null;
  15021. }
  15022. // Rescale PP
  15023. if (this._rescalePostProcess) {
  15024. this._rescalePostProcess.dispose();
  15025. }
  15026. // Release scenes
  15027. while (this.scenes.length) {
  15028. this.scenes[0].dispose();
  15029. }
  15030. // Release audio engine
  15031. if (Engine.audioEngine) {
  15032. Engine.audioEngine.dispose();
  15033. }
  15034. // Release effects
  15035. this.releaseEffects();
  15036. // Unbind
  15037. this.unbindAllAttributes();
  15038. if (this._dummyFramebuffer) {
  15039. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15040. }
  15041. //WebVR
  15042. this.disableVR();
  15043. // Events
  15044. if (BABYLON.Tools.IsWindowObjectExist()) {
  15045. window.removeEventListener("blur", this._onBlur);
  15046. window.removeEventListener("focus", this._onFocus);
  15047. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15048. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15049. if (this._renderingCanvas) {
  15050. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15051. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15052. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15053. if (!this._doNotHandleContextLost) {
  15054. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15055. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15056. }
  15057. }
  15058. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15059. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15060. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15061. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15062. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15063. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15064. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15065. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15066. if (this._onVrDisplayConnect) {
  15067. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15068. if (this._onVrDisplayDisconnect) {
  15069. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15070. }
  15071. if (this._onVrDisplayPresentChange) {
  15072. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15073. }
  15074. this._onVrDisplayConnect = null;
  15075. this._onVrDisplayDisconnect = null;
  15076. }
  15077. }
  15078. // Remove from Instances
  15079. var index = Engine.Instances.indexOf(this);
  15080. if (index >= 0) {
  15081. Engine.Instances.splice(index, 1);
  15082. }
  15083. this._workingCanvas = null;
  15084. this._workingContext = null;
  15085. this._currentBufferPointers = [];
  15086. this._renderingCanvas = null;
  15087. this._currentProgram = null;
  15088. this._bindedRenderFunction = null;
  15089. this.onResizeObservable.clear();
  15090. this.onCanvasBlurObservable.clear();
  15091. this.onCanvasFocusObservable.clear();
  15092. this.onCanvasPointerOutObservable.clear();
  15093. this.onBeginFrameObservable.clear();
  15094. this.onEndFrameObservable.clear();
  15095. BABYLON.Effect.ResetCache();
  15096. // Abort active requests
  15097. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15098. var request = _a[_i];
  15099. request.abort();
  15100. }
  15101. };
  15102. // Loading screen
  15103. Engine.prototype.displayLoadingUI = function () {
  15104. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15105. return;
  15106. }
  15107. var loadingScreen = this.loadingScreen;
  15108. if (loadingScreen) {
  15109. loadingScreen.displayLoadingUI();
  15110. }
  15111. };
  15112. Engine.prototype.hideLoadingUI = function () {
  15113. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15114. return;
  15115. }
  15116. var loadingScreen = this.loadingScreen;
  15117. if (loadingScreen) {
  15118. loadingScreen.hideLoadingUI();
  15119. }
  15120. };
  15121. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15122. get: function () {
  15123. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15124. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15125. return this._loadingScreen;
  15126. },
  15127. set: function (loadingScreen) {
  15128. this._loadingScreen = loadingScreen;
  15129. },
  15130. enumerable: true,
  15131. configurable: true
  15132. });
  15133. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15134. set: function (text) {
  15135. this.loadingScreen.loadingUIText = text;
  15136. },
  15137. enumerable: true,
  15138. configurable: true
  15139. });
  15140. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15141. set: function (color) {
  15142. this.loadingScreen.loadingUIBackgroundColor = color;
  15143. },
  15144. enumerable: true,
  15145. configurable: true
  15146. });
  15147. Engine.prototype.attachContextLostEvent = function (callback) {
  15148. if (this._renderingCanvas) {
  15149. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15150. }
  15151. };
  15152. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15153. if (this._renderingCanvas) {
  15154. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15155. }
  15156. };
  15157. Engine.prototype.getVertexShaderSource = function (program) {
  15158. var shaders = this._gl.getAttachedShaders(program);
  15159. if (!shaders) {
  15160. return null;
  15161. }
  15162. return this._gl.getShaderSource(shaders[0]);
  15163. };
  15164. Engine.prototype.getFragmentShaderSource = function (program) {
  15165. var shaders = this._gl.getAttachedShaders(program);
  15166. if (!shaders) {
  15167. return null;
  15168. }
  15169. return this._gl.getShaderSource(shaders[1]);
  15170. };
  15171. Engine.prototype.getError = function () {
  15172. return this._gl.getError();
  15173. };
  15174. // FPS
  15175. Engine.prototype.getFps = function () {
  15176. return this._fps;
  15177. };
  15178. Engine.prototype.getDeltaTime = function () {
  15179. return this._deltaTime;
  15180. };
  15181. Engine.prototype._measureFps = function () {
  15182. this._performanceMonitor.sampleFrame();
  15183. this._fps = this._performanceMonitor.averageFPS;
  15184. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15185. };
  15186. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15187. if (faceIndex === void 0) { faceIndex = -1; }
  15188. var gl = this._gl;
  15189. if (!this._dummyFramebuffer) {
  15190. var dummy = gl.createFramebuffer();
  15191. if (!dummy) {
  15192. throw new Error("Unable to create dummy framebuffer");
  15193. }
  15194. this._dummyFramebuffer = dummy;
  15195. }
  15196. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15197. if (faceIndex > -1) {
  15198. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15199. }
  15200. else {
  15201. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15202. }
  15203. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15204. var buffer;
  15205. switch (readType) {
  15206. case gl.UNSIGNED_BYTE:
  15207. buffer = new Uint8Array(4 * width * height);
  15208. readType = gl.UNSIGNED_BYTE;
  15209. break;
  15210. default:
  15211. buffer = new Float32Array(4 * width * height);
  15212. readType = gl.FLOAT;
  15213. break;
  15214. }
  15215. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15216. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15217. return buffer;
  15218. };
  15219. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15220. if (this._webGLVersion > 1) {
  15221. return this._caps.colorBufferFloat;
  15222. }
  15223. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15224. };
  15225. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15226. if (this._webGLVersion > 1) {
  15227. return this._caps.colorBufferFloat;
  15228. }
  15229. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15230. };
  15231. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15232. Engine.prototype._canRenderToFramebuffer = function (type) {
  15233. var gl = this._gl;
  15234. //clear existing errors
  15235. while (gl.getError() !== gl.NO_ERROR) { }
  15236. var successful = true;
  15237. var texture = gl.createTexture();
  15238. gl.bindTexture(gl.TEXTURE_2D, texture);
  15239. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15240. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15242. var fb = gl.createFramebuffer();
  15243. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15244. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15245. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15246. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15247. successful = successful && (gl.getError() === gl.NO_ERROR);
  15248. //try render by clearing frame buffer's color buffer
  15249. if (successful) {
  15250. gl.clear(gl.COLOR_BUFFER_BIT);
  15251. successful = successful && (gl.getError() === gl.NO_ERROR);
  15252. }
  15253. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15254. if (successful) {
  15255. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15256. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15257. var readFormat = gl.RGBA;
  15258. var readType = gl.UNSIGNED_BYTE;
  15259. var buffer = new Uint8Array(4);
  15260. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15261. successful = successful && (gl.getError() === gl.NO_ERROR);
  15262. }
  15263. //clean up
  15264. gl.deleteTexture(texture);
  15265. gl.deleteFramebuffer(fb);
  15266. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15267. //clear accumulated errors
  15268. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15269. return successful;
  15270. };
  15271. Engine.prototype._getWebGLTextureType = function (type) {
  15272. if (type === Engine.TEXTURETYPE_FLOAT) {
  15273. return this._gl.FLOAT;
  15274. }
  15275. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15276. // Add Half Float Constant.
  15277. return this._gl.HALF_FLOAT_OES;
  15278. }
  15279. return this._gl.UNSIGNED_BYTE;
  15280. };
  15281. ;
  15282. Engine.prototype._getInternalFormat = function (format) {
  15283. var internalFormat = this._gl.RGBA;
  15284. switch (format) {
  15285. case Engine.TEXTUREFORMAT_ALPHA:
  15286. internalFormat = this._gl.ALPHA;
  15287. break;
  15288. case Engine.TEXTUREFORMAT_LUMINANCE:
  15289. internalFormat = this._gl.LUMINANCE;
  15290. break;
  15291. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15292. internalFormat = this._gl.LUMINANCE_ALPHA;
  15293. break;
  15294. case Engine.TEXTUREFORMAT_RGB:
  15295. case Engine.TEXTUREFORMAT_RGB32F:
  15296. internalFormat = this._gl.RGB;
  15297. break;
  15298. case Engine.TEXTUREFORMAT_RGBA:
  15299. case Engine.TEXTUREFORMAT_RGBA32F:
  15300. internalFormat = this._gl.RGBA;
  15301. break;
  15302. case Engine.TEXTUREFORMAT_R32F:
  15303. internalFormat = this._gl.RED;
  15304. break;
  15305. case Engine.TEXTUREFORMAT_RG32F:
  15306. internalFormat = this._gl.RG;
  15307. break;
  15308. }
  15309. return internalFormat;
  15310. };
  15311. /** @ignore */
  15312. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15313. if (this._webGLVersion === 1) {
  15314. if (format) {
  15315. switch (format) {
  15316. case Engine.TEXTUREFORMAT_LUMINANCE:
  15317. return this._gl.LUMINANCE;
  15318. }
  15319. }
  15320. return this._gl.RGBA;
  15321. }
  15322. if (type === Engine.TEXTURETYPE_FLOAT) {
  15323. if (format) {
  15324. switch (format) {
  15325. case Engine.TEXTUREFORMAT_R32F:
  15326. return this._gl.R32F;
  15327. case Engine.TEXTUREFORMAT_RG32F:
  15328. return this._gl.RG32F;
  15329. case Engine.TEXTUREFORMAT_RGB32F:
  15330. return this._gl.RGB32F;
  15331. }
  15332. }
  15333. return this._gl.RGBA32F;
  15334. }
  15335. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15336. return this._gl.RGBA16F;
  15337. }
  15338. if (format) {
  15339. switch (format) {
  15340. case Engine.TEXTUREFORMAT_LUMINANCE:
  15341. return this._gl.LUMINANCE;
  15342. }
  15343. }
  15344. return this._gl.RGBA;
  15345. };
  15346. ;
  15347. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15348. if (type === Engine.TEXTURETYPE_FLOAT) {
  15349. return this._gl.RGBA32F;
  15350. }
  15351. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15352. return this._gl.RGBA16F;
  15353. }
  15354. return this._gl.RGBA8;
  15355. };
  15356. ;
  15357. Engine.prototype.createQuery = function () {
  15358. return this._gl.createQuery();
  15359. };
  15360. Engine.prototype.deleteQuery = function (query) {
  15361. this._gl.deleteQuery(query);
  15362. return this;
  15363. };
  15364. Engine.prototype.isQueryResultAvailable = function (query) {
  15365. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15366. };
  15367. Engine.prototype.getQueryResult = function (query) {
  15368. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15369. };
  15370. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15371. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15372. this._gl.beginQuery(glAlgorithm, query);
  15373. return this;
  15374. };
  15375. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15376. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15377. this._gl.endQuery(glAlgorithm);
  15378. return this;
  15379. };
  15380. /* Time queries */
  15381. Engine.prototype._createTimeQuery = function () {
  15382. var timerQuery = this._caps.timerQuery;
  15383. if (timerQuery.createQueryEXT) {
  15384. return timerQuery.createQueryEXT();
  15385. }
  15386. return this.createQuery();
  15387. };
  15388. Engine.prototype._deleteTimeQuery = function (query) {
  15389. var timerQuery = this._caps.timerQuery;
  15390. if (timerQuery.deleteQueryEXT) {
  15391. timerQuery.deleteQueryEXT(query);
  15392. return;
  15393. }
  15394. this.deleteQuery(query);
  15395. };
  15396. Engine.prototype._getTimeQueryResult = function (query) {
  15397. var timerQuery = this._caps.timerQuery;
  15398. if (timerQuery.getQueryObjectEXT) {
  15399. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15400. }
  15401. return this.getQueryResult(query);
  15402. };
  15403. Engine.prototype._getTimeQueryAvailability = function (query) {
  15404. var timerQuery = this._caps.timerQuery;
  15405. if (timerQuery.getQueryObjectEXT) {
  15406. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15407. }
  15408. return this.isQueryResultAvailable(query);
  15409. };
  15410. Engine.prototype.startTimeQuery = function () {
  15411. var timerQuery = this._caps.timerQuery;
  15412. if (!timerQuery) {
  15413. return null;
  15414. }
  15415. var token = new BABYLON._TimeToken();
  15416. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15417. if (this._caps.canUseTimestampForTimerQuery) {
  15418. token._startTimeQuery = this._createTimeQuery();
  15419. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15420. }
  15421. else {
  15422. if (this._currentNonTimestampToken) {
  15423. return this._currentNonTimestampToken;
  15424. }
  15425. token._timeElapsedQuery = this._createTimeQuery();
  15426. if (timerQuery.beginQueryEXT) {
  15427. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15428. }
  15429. else {
  15430. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15431. }
  15432. this._currentNonTimestampToken = token;
  15433. }
  15434. return token;
  15435. };
  15436. Engine.prototype.endTimeQuery = function (token) {
  15437. var timerQuery = this._caps.timerQuery;
  15438. if (!timerQuery || !token) {
  15439. return -1;
  15440. }
  15441. if (this._caps.canUseTimestampForTimerQuery) {
  15442. if (!token._startTimeQuery) {
  15443. return -1;
  15444. }
  15445. if (!token._endTimeQuery) {
  15446. token._endTimeQuery = this._createTimeQuery();
  15447. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15448. }
  15449. }
  15450. else if (!token._timeElapsedQueryEnded) {
  15451. if (!token._timeElapsedQuery) {
  15452. return -1;
  15453. }
  15454. if (timerQuery.endQueryEXT) {
  15455. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15456. }
  15457. else {
  15458. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15459. }
  15460. token._timeElapsedQueryEnded = true;
  15461. }
  15462. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15463. var available = false;
  15464. if (token._endTimeQuery) {
  15465. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15466. }
  15467. else if (token._timeElapsedQuery) {
  15468. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15469. }
  15470. if (available && !disjoint) {
  15471. var result = 0;
  15472. if (this._caps.canUseTimestampForTimerQuery) {
  15473. if (!token._startTimeQuery || !token._endTimeQuery) {
  15474. return -1;
  15475. }
  15476. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15477. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15478. result = timeEnd - timeStart;
  15479. this._deleteTimeQuery(token._startTimeQuery);
  15480. this._deleteTimeQuery(token._endTimeQuery);
  15481. token._startTimeQuery = null;
  15482. token._endTimeQuery = null;
  15483. }
  15484. else {
  15485. if (!token._timeElapsedQuery) {
  15486. return -1;
  15487. }
  15488. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15489. this._deleteTimeQuery(token._timeElapsedQuery);
  15490. token._timeElapsedQuery = null;
  15491. token._timeElapsedQueryEnded = false;
  15492. this._currentNonTimestampToken = null;
  15493. }
  15494. return result;
  15495. }
  15496. return -1;
  15497. };
  15498. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15499. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15500. };
  15501. // Transform feedback
  15502. Engine.prototype.createTransformFeedback = function () {
  15503. return this._gl.createTransformFeedback();
  15504. };
  15505. Engine.prototype.deleteTransformFeedback = function (value) {
  15506. this._gl.deleteTransformFeedback(value);
  15507. };
  15508. Engine.prototype.bindTransformFeedback = function (value) {
  15509. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15510. };
  15511. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15512. if (usePoints === void 0) { usePoints = true; }
  15513. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15514. };
  15515. Engine.prototype.endTransformFeedback = function () {
  15516. this._gl.endTransformFeedback();
  15517. };
  15518. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15519. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15520. };
  15521. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15522. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15523. };
  15524. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15525. var _this = this;
  15526. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15527. this._activeRequests.push(request);
  15528. request.onCompleteObservable.add(function (request) {
  15529. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15530. });
  15531. return request;
  15532. };
  15533. /** @ignore */
  15534. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15535. var _this = this;
  15536. return new Promise(function (resolve, reject) {
  15537. _this._loadFile(url, function (data) {
  15538. resolve(data);
  15539. }, undefined, database, useArrayBuffer, function (request, exception) {
  15540. reject(exception);
  15541. });
  15542. });
  15543. };
  15544. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15545. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15546. var onload = function (data) {
  15547. loadedFiles[index] = data;
  15548. loadedFiles._internalCount++;
  15549. if (loadedFiles._internalCount === 6) {
  15550. onfinish(loadedFiles);
  15551. }
  15552. };
  15553. var onerror = function (request, exception) {
  15554. if (onErrorCallBack && request) {
  15555. onErrorCallBack(request.status + " " + request.statusText, exception);
  15556. }
  15557. };
  15558. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15559. };
  15560. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15561. if (onError === void 0) { onError = null; }
  15562. var loadedFiles = [];
  15563. loadedFiles._internalCount = 0;
  15564. for (var index = 0; index < 6; index++) {
  15565. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15566. }
  15567. };
  15568. // Statics
  15569. Engine.isSupported = function () {
  15570. try {
  15571. var tempcanvas = document.createElement("canvas");
  15572. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15573. return gl != null && !!window.WebGLRenderingContext;
  15574. }
  15575. catch (e) {
  15576. return false;
  15577. }
  15578. };
  15579. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15580. Engine.ExceptionList = [
  15581. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15582. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15583. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15584. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15585. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15586. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15587. ];
  15588. Engine.Instances = new Array();
  15589. // Const statics
  15590. Engine._ALPHA_DISABLE = 0;
  15591. Engine._ALPHA_ADD = 1;
  15592. Engine._ALPHA_COMBINE = 2;
  15593. Engine._ALPHA_SUBTRACT = 3;
  15594. Engine._ALPHA_MULTIPLY = 4;
  15595. Engine._ALPHA_MAXIMIZED = 5;
  15596. Engine._ALPHA_ONEONE = 6;
  15597. Engine._ALPHA_PREMULTIPLIED = 7;
  15598. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15599. Engine._ALPHA_INTERPOLATE = 9;
  15600. Engine._ALPHA_SCREENMODE = 10;
  15601. Engine._DELAYLOADSTATE_NONE = 0;
  15602. Engine._DELAYLOADSTATE_LOADED = 1;
  15603. Engine._DELAYLOADSTATE_LOADING = 2;
  15604. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15605. Engine._TEXTUREFORMAT_ALPHA = 0;
  15606. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15607. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15608. Engine._TEXTUREFORMAT_RGB = 4;
  15609. Engine._TEXTUREFORMAT_RGBA = 5;
  15610. Engine._TEXTUREFORMAT_R32F = 6;
  15611. Engine._TEXTUREFORMAT_RG32F = 7;
  15612. Engine._TEXTUREFORMAT_RGB32F = 8;
  15613. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15614. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15615. Engine._TEXTURETYPE_FLOAT = 1;
  15616. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15617. // Depht or Stencil test Constants.
  15618. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15619. 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.
  15620. 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.
  15621. 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.
  15622. 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.
  15623. 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.
  15624. 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.
  15625. 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.
  15626. // Stencil Actions Constants.
  15627. Engine._KEEP = 0x1E00;
  15628. Engine._REPLACE = 0x1E01;
  15629. Engine._INCR = 0x1E02;
  15630. Engine._DECR = 0x1E03;
  15631. Engine._INVERT = 0x150A;
  15632. Engine._INCR_WRAP = 0x8507;
  15633. Engine._DECR_WRAP = 0x8508;
  15634. // Texture rescaling mode
  15635. Engine._SCALEMODE_FLOOR = 1;
  15636. Engine._SCALEMODE_NEAREST = 2;
  15637. Engine._SCALEMODE_CEILING = 3;
  15638. // Updatable statics so stick with vars here
  15639. Engine.CollisionsEpsilon = 0.001;
  15640. Engine.CodeRepository = "src/";
  15641. Engine.ShadersRepository = "src/Shaders/";
  15642. return Engine;
  15643. }());
  15644. BABYLON.Engine = Engine;
  15645. })(BABYLON || (BABYLON = {}));
  15646. //# sourceMappingURL=babylon.engine.js.map
  15647. "use strict";
  15648. var BABYLON;
  15649. (function (BABYLON) {
  15650. /**
  15651. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15652. */
  15653. var Node = /** @class */ (function () {
  15654. /**
  15655. * Creates a new Node
  15656. * @param {string} name - the name and id to be given to this node
  15657. * @param {BABYLON.Scene} the scene this node will be added to
  15658. */
  15659. function Node(name, scene) {
  15660. if (scene === void 0) { scene = null; }
  15661. /**
  15662. * Gets or sets a string used to store user defined state for the node
  15663. */
  15664. this.state = "";
  15665. /**
  15666. * Gets or sets an object used to store user defined information for the node
  15667. */
  15668. this.metadata = null;
  15669. /**
  15670. * Gets or sets a boolean used to define if the node must be serialized
  15671. */
  15672. this.doNotSerialize = false;
  15673. /** @ignore */
  15674. this._isDisposed = false;
  15675. /**
  15676. * Gets a list of {BABYLON.Animation} associated with the node
  15677. */
  15678. this.animations = new Array();
  15679. this._ranges = {};
  15680. this._isEnabled = true;
  15681. this._isReady = true;
  15682. /** @ignore */
  15683. this._currentRenderId = -1;
  15684. this._parentRenderId = -1;
  15685. this._animationPropertiesOverride = null;
  15686. /**
  15687. * An event triggered when the mesh is disposed
  15688. * @type {BABYLON.Observable}
  15689. */
  15690. this.onDisposeObservable = new BABYLON.Observable();
  15691. // Behaviors
  15692. this._behaviors = new Array();
  15693. this.name = name;
  15694. this.id = name;
  15695. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15696. this.uniqueId = this._scene.getUniqueId();
  15697. this._initCache();
  15698. }
  15699. /**
  15700. * Gets a boolean indicating if the node has been disposed
  15701. * @returns true if the node was disposed
  15702. */
  15703. Node.prototype.isDisposed = function () {
  15704. return this._isDisposed;
  15705. };
  15706. Object.defineProperty(Node.prototype, "parent", {
  15707. get: function () {
  15708. return this._parentNode;
  15709. },
  15710. /**
  15711. * Gets or sets the parent of the node
  15712. */
  15713. set: function (parent) {
  15714. if (this._parentNode === parent) {
  15715. return;
  15716. }
  15717. // Remove self from list of children of parent
  15718. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15719. var index = this._parentNode._children.indexOf(this);
  15720. if (index !== -1) {
  15721. this._parentNode._children.splice(index, 1);
  15722. }
  15723. }
  15724. // Store new parent
  15725. this._parentNode = parent;
  15726. // Add as child to new parent
  15727. if (this._parentNode) {
  15728. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15729. this._parentNode._children = new Array();
  15730. }
  15731. this._parentNode._children.push(this);
  15732. }
  15733. },
  15734. enumerable: true,
  15735. configurable: true
  15736. });
  15737. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15738. /**
  15739. * Gets or sets the animation properties override
  15740. */
  15741. get: function () {
  15742. return this._animationPropertiesOverride;
  15743. },
  15744. set: function (value) {
  15745. this._animationPropertiesOverride = value;
  15746. },
  15747. enumerable: true,
  15748. configurable: true
  15749. });
  15750. /**
  15751. * Gets a string idenfifying the name of the class
  15752. * @returns "Node" string
  15753. */
  15754. Node.prototype.getClassName = function () {
  15755. return "Node";
  15756. };
  15757. Object.defineProperty(Node.prototype, "onDispose", {
  15758. /**
  15759. * Sets a callback that will be raised when the node will be disposed
  15760. */
  15761. set: function (callback) {
  15762. if (this._onDisposeObserver) {
  15763. this.onDisposeObservable.remove(this._onDisposeObserver);
  15764. }
  15765. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15766. },
  15767. enumerable: true,
  15768. configurable: true
  15769. });
  15770. /**
  15771. * Gets the scene of the node
  15772. * @returns a {BABYLON.Scene}
  15773. */
  15774. Node.prototype.getScene = function () {
  15775. return this._scene;
  15776. };
  15777. /**
  15778. * Gets the engine of the node
  15779. * @returns a {BABYLON.Engine}
  15780. */
  15781. Node.prototype.getEngine = function () {
  15782. return this._scene.getEngine();
  15783. };
  15784. /**
  15785. * Attach a behavior to the node
  15786. * @see http://doc.babylonjs.com/features/behaviour
  15787. * @param behavior defines the behavior to attach
  15788. * @returns the current Node
  15789. */
  15790. Node.prototype.addBehavior = function (behavior) {
  15791. var _this = this;
  15792. var index = this._behaviors.indexOf(behavior);
  15793. if (index !== -1) {
  15794. return this;
  15795. }
  15796. behavior.init();
  15797. if (this._scene.isLoading) {
  15798. // We defer the attach when the scene will be loaded
  15799. var observer = this._scene.onDataLoadedObservable.add(function () {
  15800. behavior.attach(_this);
  15801. setTimeout(function () {
  15802. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15803. _this._scene.onDataLoadedObservable.remove(observer);
  15804. }, 0);
  15805. });
  15806. }
  15807. else {
  15808. behavior.attach(this);
  15809. }
  15810. this._behaviors.push(behavior);
  15811. return this;
  15812. };
  15813. /**
  15814. * Remove an attached behavior
  15815. * @see http://doc.babylonjs.com/features/behaviour
  15816. * @param behavior defines the behavior to attach
  15817. * @returns the current Node
  15818. */
  15819. Node.prototype.removeBehavior = function (behavior) {
  15820. var index = this._behaviors.indexOf(behavior);
  15821. if (index === -1) {
  15822. return this;
  15823. }
  15824. this._behaviors[index].detach();
  15825. this._behaviors.splice(index, 1);
  15826. return this;
  15827. };
  15828. Object.defineProperty(Node.prototype, "behaviors", {
  15829. /**
  15830. * Gets the list of attached behaviors
  15831. * @see http://doc.babylonjs.com/features/behaviour
  15832. */
  15833. get: function () {
  15834. return this._behaviors;
  15835. },
  15836. enumerable: true,
  15837. configurable: true
  15838. });
  15839. /**
  15840. * Gets an attached behavior by name
  15841. * @param name defines the name of the behavior to look for
  15842. * @see http://doc.babylonjs.com/features/behaviour
  15843. * @returns null if behavior was not found else the requested behavior
  15844. */
  15845. Node.prototype.getBehaviorByName = function (name) {
  15846. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15847. var behavior = _a[_i];
  15848. if (behavior.name === name) {
  15849. return behavior;
  15850. }
  15851. }
  15852. return null;
  15853. };
  15854. /**
  15855. * Returns the world matrix of the node
  15856. * @returns a matrix containing the node's world matrix
  15857. */
  15858. Node.prototype.getWorldMatrix = function () {
  15859. return BABYLON.Matrix.Identity();
  15860. };
  15861. // override it in derived class if you add new variables to the cache
  15862. // and call the parent class method
  15863. /** @ignore */
  15864. Node.prototype._initCache = function () {
  15865. this._cache = {};
  15866. this._cache.parent = undefined;
  15867. };
  15868. /** @ignore */
  15869. Node.prototype.updateCache = function (force) {
  15870. if (!force && this.isSynchronized())
  15871. return;
  15872. this._cache.parent = this.parent;
  15873. this._updateCache();
  15874. };
  15875. // override it in derived class if you add new variables to the cache
  15876. // and call the parent class method if !ignoreParentClass
  15877. /** @ignore */
  15878. Node.prototype._updateCache = function (ignoreParentClass) {
  15879. };
  15880. // override it in derived class if you add new variables to the cache
  15881. /** @ignore */
  15882. Node.prototype._isSynchronized = function () {
  15883. return true;
  15884. };
  15885. /** @ignore */
  15886. Node.prototype._markSyncedWithParent = function () {
  15887. if (this.parent) {
  15888. this._parentRenderId = this.parent._currentRenderId;
  15889. }
  15890. };
  15891. /** @ignore */
  15892. Node.prototype.isSynchronizedWithParent = function () {
  15893. if (!this.parent) {
  15894. return true;
  15895. }
  15896. if (this._parentRenderId !== this.parent._currentRenderId) {
  15897. return false;
  15898. }
  15899. return this.parent.isSynchronized();
  15900. };
  15901. /** @ignore */
  15902. Node.prototype.isSynchronized = function (updateCache) {
  15903. var check = this.hasNewParent();
  15904. check = check || !this.isSynchronizedWithParent();
  15905. check = check || !this._isSynchronized();
  15906. if (updateCache)
  15907. this.updateCache(true);
  15908. return !check;
  15909. };
  15910. /** @ignore */
  15911. Node.prototype.hasNewParent = function (update) {
  15912. if (this._cache.parent === this.parent)
  15913. return false;
  15914. if (update)
  15915. this._cache.parent = this.parent;
  15916. return true;
  15917. };
  15918. /**
  15919. * Is this node ready to be used/rendered
  15920. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15921. * @return true if the node is ready
  15922. */
  15923. Node.prototype.isReady = function (completeCheck) {
  15924. if (completeCheck === void 0) { completeCheck = false; }
  15925. return this._isReady;
  15926. };
  15927. /**
  15928. * Is this node enabled?
  15929. * 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
  15930. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  15931. * @return whether this node (and its parent) is enabled
  15932. * @see setEnabled
  15933. */
  15934. Node.prototype.isEnabled = function (checkAncestors) {
  15935. if (checkAncestors === void 0) { checkAncestors = true; }
  15936. if (checkAncestors === false) {
  15937. return this._isEnabled;
  15938. }
  15939. if (this._isEnabled === false) {
  15940. return false;
  15941. }
  15942. if (this.parent !== undefined && this.parent !== null) {
  15943. return this.parent.isEnabled(checkAncestors);
  15944. }
  15945. return true;
  15946. };
  15947. /**
  15948. * Set the enabled state of this node
  15949. * @param value defines the new enabled state
  15950. * @see isEnabled
  15951. */
  15952. Node.prototype.setEnabled = function (value) {
  15953. this._isEnabled = value;
  15954. };
  15955. /**
  15956. * Is this node a descendant of the given node?
  15957. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15958. * @param ancestor defines the parent node to inspect
  15959. * @see parent
  15960. * @returns a boolean indicating if this node is a descendant of the given node
  15961. */
  15962. Node.prototype.isDescendantOf = function (ancestor) {
  15963. if (this.parent) {
  15964. if (this.parent === ancestor) {
  15965. return true;
  15966. }
  15967. return this.parent.isDescendantOf(ancestor);
  15968. }
  15969. return false;
  15970. };
  15971. /** @ignore */
  15972. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15973. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15974. if (!this._children) {
  15975. return;
  15976. }
  15977. for (var index = 0; index < this._children.length; index++) {
  15978. var item = this._children[index];
  15979. if (!predicate || predicate(item)) {
  15980. results.push(item);
  15981. }
  15982. if (!directDescendantsOnly) {
  15983. item._getDescendants(results, false, predicate);
  15984. }
  15985. }
  15986. };
  15987. /**
  15988. * Will return all nodes that have this node as ascendant
  15989. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  15990. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  15991. * @return all children nodes of all types
  15992. */
  15993. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15994. var results = new Array();
  15995. this._getDescendants(results, directDescendantsOnly, predicate);
  15996. return results;
  15997. };
  15998. /**
  15999. * Get all child-meshes of this node
  16000. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  16001. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  16002. * @returns an array of {BABYLON.AbstractMesh}
  16003. */
  16004. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  16005. var results = [];
  16006. this._getDescendants(results, directDescendantsOnly, function (node) {
  16007. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  16008. });
  16009. return results;
  16010. };
  16011. /**
  16012. * Get all child-transformNodes of this node
  16013. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  16014. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  16015. * @returns an array of {BABYLON.TransformNode}
  16016. */
  16017. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  16018. var results = [];
  16019. this._getDescendants(results, directDescendantsOnly, function (node) {
  16020. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  16021. });
  16022. return results;
  16023. };
  16024. /**
  16025. * Get all direct children of this node
  16026. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  16027. * @returns an array of {BABYLON.Node}
  16028. */
  16029. Node.prototype.getChildren = function (predicate) {
  16030. return this.getDescendants(true, predicate);
  16031. };
  16032. /** @ignore */
  16033. Node.prototype._setReady = function (state) {
  16034. if (state === this._isReady) {
  16035. return;
  16036. }
  16037. if (!state) {
  16038. this._isReady = false;
  16039. return;
  16040. }
  16041. if (this.onReady) {
  16042. this.onReady(this);
  16043. }
  16044. this._isReady = true;
  16045. };
  16046. /**
  16047. * Get an animation by name
  16048. * @param name defines the name of the animation to look for
  16049. * @returns null if not found else the requested animation
  16050. */
  16051. Node.prototype.getAnimationByName = function (name) {
  16052. for (var i = 0; i < this.animations.length; i++) {
  16053. var animation = this.animations[i];
  16054. if (animation.name === name) {
  16055. return animation;
  16056. }
  16057. }
  16058. return null;
  16059. };
  16060. /**
  16061. * Creates an animation range for this node
  16062. * @param name defines the name of the range
  16063. * @param from defines the starting key
  16064. * @param to defines the end key
  16065. */
  16066. Node.prototype.createAnimationRange = function (name, from, to) {
  16067. // check name not already in use
  16068. if (!this._ranges[name]) {
  16069. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16070. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16071. if (this.animations[i]) {
  16072. this.animations[i].createRange(name, from, to);
  16073. }
  16074. }
  16075. }
  16076. };
  16077. /**
  16078. * Delete a specific animation range
  16079. * @param name defines the name of the range to delete
  16080. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16081. */
  16082. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16083. if (deleteFrames === void 0) { deleteFrames = true; }
  16084. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16085. if (this.animations[i]) {
  16086. this.animations[i].deleteRange(name, deleteFrames);
  16087. }
  16088. }
  16089. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16090. };
  16091. /**
  16092. * Get an animation range by name
  16093. * @param name defines the name of the animation range to look for
  16094. * @returns null if not found else the requested animation range
  16095. */
  16096. Node.prototype.getAnimationRange = function (name) {
  16097. return this._ranges[name];
  16098. };
  16099. /**
  16100. * Will start the animation sequence
  16101. * @param name defines the range frames for animation sequence
  16102. * @param loop defines if the animation should loop (false by default)
  16103. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16104. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16105. * @returns the object created for this animation. If range does not exist, it will return null
  16106. */
  16107. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16108. var range = this.getAnimationRange(name);
  16109. if (!range) {
  16110. return null;
  16111. }
  16112. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16113. };
  16114. /**
  16115. * Serialize animation ranges into a JSON compatible object
  16116. * @returns serialization object
  16117. */
  16118. Node.prototype.serializeAnimationRanges = function () {
  16119. var serializationRanges = [];
  16120. for (var name in this._ranges) {
  16121. var localRange = this._ranges[name];
  16122. if (!localRange) {
  16123. continue;
  16124. }
  16125. var range = {};
  16126. range.name = name;
  16127. range.from = localRange.from;
  16128. range.to = localRange.to;
  16129. serializationRanges.push(range);
  16130. }
  16131. return serializationRanges;
  16132. };
  16133. /**
  16134. * Computes the world matrix of the node
  16135. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16136. * @returns the world matrix
  16137. */
  16138. Node.prototype.computeWorldMatrix = function (force) {
  16139. return BABYLON.Matrix.Identity();
  16140. };
  16141. /**
  16142. * Releases resources associated with this node.
  16143. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16144. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16145. */
  16146. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16147. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16148. if (!doNotRecurse) {
  16149. var nodes = this.getDescendants(true);
  16150. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16151. var node = nodes_1[_i];
  16152. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16153. }
  16154. }
  16155. else {
  16156. var transformNodes = this.getChildTransformNodes(true);
  16157. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16158. var transformNode = transformNodes_1[_a];
  16159. transformNode.parent = null;
  16160. transformNode.computeWorldMatrix(true);
  16161. }
  16162. }
  16163. this.parent = null;
  16164. // Callback
  16165. this.onDisposeObservable.notifyObservers(this);
  16166. this.onDisposeObservable.clear();
  16167. // Behaviors
  16168. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16169. var behavior = _c[_b];
  16170. behavior.detach();
  16171. }
  16172. this._behaviors = [];
  16173. this._isDisposed = true;
  16174. };
  16175. /**
  16176. * Parse animation range data from a serialization object and store them into a given node
  16177. * @param node defines where to store the animation ranges
  16178. * @param parsedNode defines the serialization object to read data from
  16179. * @param scene defines the hosting scene
  16180. */
  16181. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16182. if (parsedNode.ranges) {
  16183. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16184. var data = parsedNode.ranges[index];
  16185. node.createAnimationRange(data.name, data.from, data.to);
  16186. }
  16187. }
  16188. };
  16189. __decorate([
  16190. BABYLON.serialize()
  16191. ], Node.prototype, "name", void 0);
  16192. __decorate([
  16193. BABYLON.serialize()
  16194. ], Node.prototype, "id", void 0);
  16195. __decorate([
  16196. BABYLON.serialize()
  16197. ], Node.prototype, "uniqueId", void 0);
  16198. __decorate([
  16199. BABYLON.serialize()
  16200. ], Node.prototype, "state", void 0);
  16201. __decorate([
  16202. BABYLON.serialize()
  16203. ], Node.prototype, "metadata", void 0);
  16204. return Node;
  16205. }());
  16206. BABYLON.Node = Node;
  16207. })(BABYLON || (BABYLON = {}));
  16208. //# sourceMappingURL=babylon.node.js.map
  16209. "use strict";
  16210. var BABYLON;
  16211. (function (BABYLON) {
  16212. var BoundingSphere = /** @class */ (function () {
  16213. function BoundingSphere(minimum, maximum) {
  16214. this.minimum = minimum;
  16215. this.maximum = maximum;
  16216. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16217. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16218. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16219. this.radius = distance * 0.5;
  16220. this.centerWorld = BABYLON.Vector3.Zero();
  16221. this._update(BABYLON.Matrix.Identity());
  16222. }
  16223. // Methods
  16224. BoundingSphere.prototype._update = function (world) {
  16225. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16226. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16227. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16228. };
  16229. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16230. for (var i = 0; i < 6; i++) {
  16231. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16232. return false;
  16233. }
  16234. return true;
  16235. };
  16236. BoundingSphere.prototype.intersectsPoint = function (point) {
  16237. var x = this.centerWorld.x - point.x;
  16238. var y = this.centerWorld.y - point.y;
  16239. var z = this.centerWorld.z - point.z;
  16240. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16241. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16242. return false;
  16243. return true;
  16244. };
  16245. // Statics
  16246. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16247. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16248. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16249. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16250. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16251. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16252. return false;
  16253. return true;
  16254. };
  16255. return BoundingSphere;
  16256. }());
  16257. BABYLON.BoundingSphere = BoundingSphere;
  16258. })(BABYLON || (BABYLON = {}));
  16259. //# sourceMappingURL=babylon.boundingSphere.js.map
  16260. "use strict";
  16261. var BABYLON;
  16262. (function (BABYLON) {
  16263. var BoundingBox = /** @class */ (function () {
  16264. function BoundingBox(minimum, maximum) {
  16265. this.minimum = minimum;
  16266. this.maximum = maximum;
  16267. this.vectors = new Array();
  16268. this.vectorsWorld = new Array();
  16269. // Bounding vectors
  16270. this.vectors.push(this.minimum.clone());
  16271. this.vectors.push(this.maximum.clone());
  16272. this.vectors.push(this.minimum.clone());
  16273. this.vectors[2].x = this.maximum.x;
  16274. this.vectors.push(this.minimum.clone());
  16275. this.vectors[3].y = this.maximum.y;
  16276. this.vectors.push(this.minimum.clone());
  16277. this.vectors[4].z = this.maximum.z;
  16278. this.vectors.push(this.maximum.clone());
  16279. this.vectors[5].z = this.minimum.z;
  16280. this.vectors.push(this.maximum.clone());
  16281. this.vectors[6].x = this.minimum.x;
  16282. this.vectors.push(this.maximum.clone());
  16283. this.vectors[7].y = this.minimum.y;
  16284. // OBB
  16285. this.center = this.maximum.add(this.minimum).scale(0.5);
  16286. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16287. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16288. // World
  16289. for (var index = 0; index < this.vectors.length; index++) {
  16290. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16291. }
  16292. this.minimumWorld = BABYLON.Vector3.Zero();
  16293. this.maximumWorld = BABYLON.Vector3.Zero();
  16294. this.centerWorld = BABYLON.Vector3.Zero();
  16295. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16296. this._update(BABYLON.Matrix.Identity());
  16297. }
  16298. // Methods
  16299. BoundingBox.prototype.getWorldMatrix = function () {
  16300. return this._worldMatrix;
  16301. };
  16302. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16303. this._worldMatrix.copyFrom(matrix);
  16304. return this;
  16305. };
  16306. BoundingBox.prototype._update = function (world) {
  16307. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16308. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16309. for (var index = 0; index < this.vectors.length; index++) {
  16310. var v = this.vectorsWorld[index];
  16311. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16312. if (v.x < this.minimumWorld.x)
  16313. this.minimumWorld.x = v.x;
  16314. if (v.y < this.minimumWorld.y)
  16315. this.minimumWorld.y = v.y;
  16316. if (v.z < this.minimumWorld.z)
  16317. this.minimumWorld.z = v.z;
  16318. if (v.x > this.maximumWorld.x)
  16319. this.maximumWorld.x = v.x;
  16320. if (v.y > this.maximumWorld.y)
  16321. this.maximumWorld.y = v.y;
  16322. if (v.z > this.maximumWorld.z)
  16323. this.maximumWorld.z = v.z;
  16324. }
  16325. // Extend
  16326. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16327. this.extendSizeWorld.scaleInPlace(0.5);
  16328. // OBB
  16329. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16330. this.centerWorld.scaleInPlace(0.5);
  16331. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16332. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16333. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16334. this._worldMatrix = world;
  16335. };
  16336. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16337. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16338. };
  16339. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16340. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16341. };
  16342. BoundingBox.prototype.intersectsPoint = function (point) {
  16343. var delta = -BABYLON.Epsilon;
  16344. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16345. return false;
  16346. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16347. return false;
  16348. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16349. return false;
  16350. return true;
  16351. };
  16352. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16353. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16354. };
  16355. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16356. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16357. return false;
  16358. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16359. return false;
  16360. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16361. return false;
  16362. return true;
  16363. };
  16364. // Statics
  16365. BoundingBox.Intersects = function (box0, box1) {
  16366. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16367. return false;
  16368. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16369. return false;
  16370. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16371. return false;
  16372. return true;
  16373. };
  16374. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16375. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16376. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16377. return (num <= (sphereRadius * sphereRadius));
  16378. };
  16379. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16380. for (var p = 0; p < 6; p++) {
  16381. for (var i = 0; i < 8; i++) {
  16382. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16383. return false;
  16384. }
  16385. }
  16386. }
  16387. return true;
  16388. };
  16389. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16390. for (var p = 0; p < 6; p++) {
  16391. var inCount = 8;
  16392. for (var i = 0; i < 8; i++) {
  16393. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16394. --inCount;
  16395. }
  16396. else {
  16397. break;
  16398. }
  16399. }
  16400. if (inCount === 0)
  16401. return false;
  16402. }
  16403. return true;
  16404. };
  16405. return BoundingBox;
  16406. }());
  16407. BABYLON.BoundingBox = BoundingBox;
  16408. })(BABYLON || (BABYLON = {}));
  16409. //# sourceMappingURL=babylon.boundingBox.js.map
  16410. "use strict";
  16411. var BABYLON;
  16412. (function (BABYLON) {
  16413. var computeBoxExtents = function (axis, box) {
  16414. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16415. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16416. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16417. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16418. var r = r0 + r1 + r2;
  16419. return {
  16420. min: p - r,
  16421. max: p + r
  16422. };
  16423. };
  16424. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16425. var axisOverlap = function (axis, box0, box1) {
  16426. var result0 = computeBoxExtents(axis, box0);
  16427. var result1 = computeBoxExtents(axis, box1);
  16428. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16429. };
  16430. var BoundingInfo = /** @class */ (function () {
  16431. function BoundingInfo(minimum, maximum) {
  16432. this.minimum = minimum;
  16433. this.maximum = maximum;
  16434. this._isLocked = false;
  16435. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16436. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16437. }
  16438. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16439. get: function () {
  16440. return this._isLocked;
  16441. },
  16442. set: function (value) {
  16443. this._isLocked = value;
  16444. },
  16445. enumerable: true,
  16446. configurable: true
  16447. });
  16448. // Methods
  16449. BoundingInfo.prototype.update = function (world) {
  16450. if (this._isLocked) {
  16451. return;
  16452. }
  16453. this.boundingBox._update(world);
  16454. this.boundingSphere._update(world);
  16455. };
  16456. /**
  16457. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16458. * @param center New center of the bounding info
  16459. * @param extend New extend of the bounding info
  16460. */
  16461. BoundingInfo.prototype.centerOn = function (center, extend) {
  16462. this.minimum = center.subtract(extend);
  16463. this.maximum = center.add(extend);
  16464. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16465. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16466. return this;
  16467. };
  16468. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16469. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16470. return false;
  16471. return this.boundingBox.isInFrustum(frustumPlanes);
  16472. };
  16473. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16474. /**
  16475. * Gets the world distance between the min and max points of the bounding box
  16476. */
  16477. get: function () {
  16478. var boundingBox = this.boundingBox;
  16479. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16480. return size.length();
  16481. },
  16482. enumerable: true,
  16483. configurable: true
  16484. });
  16485. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16486. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16487. };
  16488. BoundingInfo.prototype._checkCollision = function (collider) {
  16489. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16490. };
  16491. BoundingInfo.prototype.intersectsPoint = function (point) {
  16492. if (!this.boundingSphere.centerWorld) {
  16493. return false;
  16494. }
  16495. if (!this.boundingSphere.intersectsPoint(point)) {
  16496. return false;
  16497. }
  16498. if (!this.boundingBox.intersectsPoint(point)) {
  16499. return false;
  16500. }
  16501. return true;
  16502. };
  16503. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16504. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16505. return false;
  16506. }
  16507. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16508. return false;
  16509. }
  16510. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16511. return false;
  16512. }
  16513. if (!precise) {
  16514. return true;
  16515. }
  16516. var box0 = this.boundingBox;
  16517. var box1 = boundingInfo.boundingBox;
  16518. if (!axisOverlap(box0.directions[0], box0, box1))
  16519. return false;
  16520. if (!axisOverlap(box0.directions[1], box0, box1))
  16521. return false;
  16522. if (!axisOverlap(box0.directions[2], box0, box1))
  16523. return false;
  16524. if (!axisOverlap(box1.directions[0], box0, box1))
  16525. return false;
  16526. if (!axisOverlap(box1.directions[1], box0, box1))
  16527. return false;
  16528. if (!axisOverlap(box1.directions[2], box0, box1))
  16529. return false;
  16530. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16531. return false;
  16532. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16533. return false;
  16534. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16535. return false;
  16536. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16537. return false;
  16538. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16539. return false;
  16540. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16541. return false;
  16542. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16543. return false;
  16544. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16545. return false;
  16546. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16547. return false;
  16548. return true;
  16549. };
  16550. return BoundingInfo;
  16551. }());
  16552. BABYLON.BoundingInfo = BoundingInfo;
  16553. })(BABYLON || (BABYLON = {}));
  16554. //# sourceMappingURL=babylon.boundingInfo.js.map
  16555. "use strict";
  16556. var BABYLON;
  16557. (function (BABYLON) {
  16558. var TransformNode = /** @class */ (function (_super) {
  16559. __extends(TransformNode, _super);
  16560. function TransformNode(name, scene, isPure) {
  16561. if (scene === void 0) { scene = null; }
  16562. if (isPure === void 0) { isPure = true; }
  16563. var _this = _super.call(this, name, scene) || this;
  16564. // Properties
  16565. _this._rotation = BABYLON.Vector3.Zero();
  16566. _this._scaling = BABYLON.Vector3.One();
  16567. _this._isDirty = false;
  16568. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16569. _this.scalingDeterminant = 1;
  16570. _this.infiniteDistance = false;
  16571. _this.position = BABYLON.Vector3.Zero();
  16572. _this._localWorld = BABYLON.Matrix.Zero();
  16573. _this._worldMatrix = BABYLON.Matrix.Zero();
  16574. _this._worldMatrixDeterminant = 0;
  16575. _this._absolutePosition = BABYLON.Vector3.Zero();
  16576. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16577. _this._postMultiplyPivotMatrix = false;
  16578. _this._isWorldMatrixFrozen = false;
  16579. /**
  16580. * An event triggered after the world matrix is updated
  16581. * @type {BABYLON.Observable}
  16582. */
  16583. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16584. _this._nonUniformScaling = false;
  16585. if (isPure) {
  16586. _this.getScene().addTransformNode(_this);
  16587. }
  16588. return _this;
  16589. }
  16590. /**
  16591. * Gets a string idenfifying the name of the class
  16592. * @returns "TransformNode" string
  16593. */
  16594. TransformNode.prototype.getClassName = function () {
  16595. return "TransformNode";
  16596. };
  16597. Object.defineProperty(TransformNode.prototype, "rotation", {
  16598. /**
  16599. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16600. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16601. * Default : (0.0, 0.0, 0.0)
  16602. */
  16603. get: function () {
  16604. return this._rotation;
  16605. },
  16606. set: function (newRotation) {
  16607. this._rotation = newRotation;
  16608. },
  16609. enumerable: true,
  16610. configurable: true
  16611. });
  16612. Object.defineProperty(TransformNode.prototype, "scaling", {
  16613. /**
  16614. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16615. * Default : (1.0, 1.0, 1.0)
  16616. */
  16617. get: function () {
  16618. return this._scaling;
  16619. },
  16620. /**
  16621. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16622. * Default : (1.0, 1.0, 1.0)
  16623. */
  16624. set: function (newScaling) {
  16625. this._scaling = newScaling;
  16626. },
  16627. enumerable: true,
  16628. configurable: true
  16629. });
  16630. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16631. /**
  16632. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16633. * It's null by default.
  16634. * 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)
  16635. */
  16636. get: function () {
  16637. return this._rotationQuaternion;
  16638. },
  16639. set: function (quaternion) {
  16640. this._rotationQuaternion = quaternion;
  16641. //reset the rotation vector.
  16642. if (quaternion && this.rotation.length()) {
  16643. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16644. }
  16645. },
  16646. enumerable: true,
  16647. configurable: true
  16648. });
  16649. /**
  16650. * Returns the latest update of the World matrix
  16651. * Returns a Matrix.
  16652. */
  16653. TransformNode.prototype.getWorldMatrix = function () {
  16654. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16655. this.computeWorldMatrix();
  16656. }
  16657. return this._worldMatrix;
  16658. };
  16659. /**
  16660. * Returns the latest update of the World matrix determinant.
  16661. */
  16662. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16663. return this._worldMatrixDeterminant;
  16664. };
  16665. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16666. /**
  16667. * Returns directly the latest state of the mesh World matrix.
  16668. * A Matrix is returned.
  16669. */
  16670. get: function () {
  16671. return this._worldMatrix;
  16672. },
  16673. enumerable: true,
  16674. configurable: true
  16675. });
  16676. /**
  16677. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16678. * Returns the AbstractMesh.
  16679. */
  16680. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16681. this._poseMatrix.copyFrom(matrix);
  16682. return this;
  16683. };
  16684. /**
  16685. * Returns the mesh Pose matrix.
  16686. * Returned object : Matrix
  16687. */
  16688. TransformNode.prototype.getPoseMatrix = function () {
  16689. return this._poseMatrix;
  16690. };
  16691. TransformNode.prototype._isSynchronized = function () {
  16692. if (this._isDirty) {
  16693. return false;
  16694. }
  16695. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16696. return false;
  16697. if (this._cache.pivotMatrixUpdated) {
  16698. return false;
  16699. }
  16700. if (this.infiniteDistance) {
  16701. return false;
  16702. }
  16703. if (!this._cache.position.equals(this.position))
  16704. return false;
  16705. if (this.rotationQuaternion) {
  16706. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16707. return false;
  16708. }
  16709. if (!this._cache.rotation.equals(this.rotation))
  16710. return false;
  16711. if (!this._cache.scaling.equals(this.scaling))
  16712. return false;
  16713. return true;
  16714. };
  16715. TransformNode.prototype._initCache = function () {
  16716. _super.prototype._initCache.call(this);
  16717. this._cache.localMatrixUpdated = false;
  16718. this._cache.position = BABYLON.Vector3.Zero();
  16719. this._cache.scaling = BABYLON.Vector3.Zero();
  16720. this._cache.rotation = BABYLON.Vector3.Zero();
  16721. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16722. this._cache.billboardMode = -1;
  16723. };
  16724. TransformNode.prototype.markAsDirty = function (property) {
  16725. if (property === "rotation") {
  16726. this.rotationQuaternion = null;
  16727. }
  16728. this._currentRenderId = Number.MAX_VALUE;
  16729. this._isDirty = true;
  16730. return this;
  16731. };
  16732. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16733. /**
  16734. * Returns the current mesh absolute position.
  16735. * Retuns a Vector3.
  16736. */
  16737. get: function () {
  16738. return this._absolutePosition;
  16739. },
  16740. enumerable: true,
  16741. configurable: true
  16742. });
  16743. /**
  16744. * Sets a new matrix to apply before all other transformation
  16745. * @param matrix defines the transform matrix
  16746. * @returns the current TransformNode
  16747. */
  16748. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16749. return this.setPivotMatrix(matrix, false);
  16750. };
  16751. /**
  16752. * Sets a new pivot matrix to the current node
  16753. * @param matrix defines the new pivot matrix to use
  16754. * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
  16755. * @returns the current TransformNode
  16756. */
  16757. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16758. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16759. this._pivotMatrix = matrix.clone();
  16760. this._cache.pivotMatrixUpdated = true;
  16761. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16762. if (this._postMultiplyPivotMatrix) {
  16763. if (!this._pivotMatrixInverse) {
  16764. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16765. }
  16766. else {
  16767. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16768. }
  16769. }
  16770. return this;
  16771. };
  16772. /**
  16773. * Returns the mesh pivot matrix.
  16774. * Default : Identity.
  16775. * A Matrix is returned.
  16776. */
  16777. TransformNode.prototype.getPivotMatrix = function () {
  16778. return this._pivotMatrix;
  16779. };
  16780. /**
  16781. * Prevents the World matrix to be computed any longer.
  16782. * Returns the AbstractMesh.
  16783. */
  16784. TransformNode.prototype.freezeWorldMatrix = function () {
  16785. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16786. this.computeWorldMatrix(true);
  16787. this._isWorldMatrixFrozen = true;
  16788. return this;
  16789. };
  16790. /**
  16791. * Allows back the World matrix computation.
  16792. * Returns the AbstractMesh.
  16793. */
  16794. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16795. this._isWorldMatrixFrozen = false;
  16796. this.computeWorldMatrix(true);
  16797. return this;
  16798. };
  16799. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16800. /**
  16801. * True if the World matrix has been frozen.
  16802. * Returns a boolean.
  16803. */
  16804. get: function () {
  16805. return this._isWorldMatrixFrozen;
  16806. },
  16807. enumerable: true,
  16808. configurable: true
  16809. });
  16810. /**
  16811. * Retuns the mesh absolute position in the World.
  16812. * Returns a Vector3.
  16813. */
  16814. TransformNode.prototype.getAbsolutePosition = function () {
  16815. this.computeWorldMatrix();
  16816. return this._absolutePosition;
  16817. };
  16818. /**
  16819. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16820. * Returns the AbstractMesh.
  16821. */
  16822. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16823. if (!absolutePosition) {
  16824. return this;
  16825. }
  16826. var absolutePositionX;
  16827. var absolutePositionY;
  16828. var absolutePositionZ;
  16829. if (absolutePosition.x === undefined) {
  16830. if (arguments.length < 3) {
  16831. return this;
  16832. }
  16833. absolutePositionX = arguments[0];
  16834. absolutePositionY = arguments[1];
  16835. absolutePositionZ = arguments[2];
  16836. }
  16837. else {
  16838. absolutePositionX = absolutePosition.x;
  16839. absolutePositionY = absolutePosition.y;
  16840. absolutePositionZ = absolutePosition.z;
  16841. }
  16842. if (this.parent) {
  16843. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16844. invertParentWorldMatrix.invert();
  16845. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16846. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16847. }
  16848. else {
  16849. this.position.x = absolutePositionX;
  16850. this.position.y = absolutePositionY;
  16851. this.position.z = absolutePositionZ;
  16852. }
  16853. return this;
  16854. };
  16855. /**
  16856. * Sets the mesh position in its local space.
  16857. * Returns the AbstractMesh.
  16858. */
  16859. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16860. this.computeWorldMatrix();
  16861. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16862. return this;
  16863. };
  16864. /**
  16865. * Returns the mesh position in the local space from the current World matrix values.
  16866. * Returns a new Vector3.
  16867. */
  16868. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16869. this.computeWorldMatrix();
  16870. var invLocalWorldMatrix = this._localWorld.clone();
  16871. invLocalWorldMatrix.invert();
  16872. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16873. };
  16874. /**
  16875. * Translates the mesh along the passed Vector3 in its local space.
  16876. * Returns the AbstractMesh.
  16877. */
  16878. TransformNode.prototype.locallyTranslate = function (vector3) {
  16879. this.computeWorldMatrix(true);
  16880. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16881. return this;
  16882. };
  16883. /**
  16884. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16885. * @param targetPoint the position (must be in same space as current mesh) to look at
  16886. * @param yawCor optional yaw (y-axis) correction in radians
  16887. * @param pitchCor optional pitch (x-axis) correction in radians
  16888. * @param rollCor optional roll (z-axis) correction in radians
  16889. * @param space the choosen space of the target
  16890. * @returns the TransformNode.
  16891. */
  16892. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16893. if (yawCor === void 0) { yawCor = 0; }
  16894. if (pitchCor === void 0) { pitchCor = 0; }
  16895. if (rollCor === void 0) { rollCor = 0; }
  16896. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16897. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16898. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16899. targetPoint.subtractToRef(pos, dv);
  16900. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16901. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16902. var pitch = Math.atan2(dv.y, len);
  16903. if (this.rotationQuaternion) {
  16904. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16905. }
  16906. else {
  16907. this.rotation.x = pitch + pitchCor;
  16908. this.rotation.y = yaw + yawCor;
  16909. this.rotation.z = rollCor;
  16910. }
  16911. return this;
  16912. };
  16913. /**
  16914. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16915. * This Vector3 is expressed in the World space.
  16916. */
  16917. TransformNode.prototype.getDirection = function (localAxis) {
  16918. var result = BABYLON.Vector3.Zero();
  16919. this.getDirectionToRef(localAxis, result);
  16920. return result;
  16921. };
  16922. /**
  16923. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16924. * localAxis is expressed in the mesh local space.
  16925. * result is computed in the Wordl space from the mesh World matrix.
  16926. * Returns the AbstractMesh.
  16927. */
  16928. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16929. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16930. return this;
  16931. };
  16932. /**
  16933. * Sets a new pivot point to the current node
  16934. * @param point defines the new pivot point to use
  16935. * @param space defines if the point is in world or local space (local by default)
  16936. * @returns the current TransformNode
  16937. */
  16938. TransformNode.prototype.setPivotPoint = function (point, space) {
  16939. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16940. if (this.getScene().getRenderId() == 0) {
  16941. this.computeWorldMatrix(true);
  16942. }
  16943. var wm = this.getWorldMatrix();
  16944. if (space == BABYLON.Space.WORLD) {
  16945. var tmat = BABYLON.Tmp.Matrix[0];
  16946. wm.invertToRef(tmat);
  16947. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16948. }
  16949. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16950. };
  16951. /**
  16952. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16953. */
  16954. TransformNode.prototype.getPivotPoint = function () {
  16955. var point = BABYLON.Vector3.Zero();
  16956. this.getPivotPointToRef(point);
  16957. return point;
  16958. };
  16959. /**
  16960. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16961. * Returns the AbstractMesh.
  16962. */
  16963. TransformNode.prototype.getPivotPointToRef = function (result) {
  16964. result.x = -this._pivotMatrix.m[12];
  16965. result.y = -this._pivotMatrix.m[13];
  16966. result.z = -this._pivotMatrix.m[14];
  16967. return this;
  16968. };
  16969. /**
  16970. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16971. */
  16972. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16973. var point = BABYLON.Vector3.Zero();
  16974. this.getAbsolutePivotPointToRef(point);
  16975. return point;
  16976. };
  16977. /**
  16978. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16979. * Returns the AbstractMesh.
  16980. */
  16981. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16982. result.x = this._pivotMatrix.m[12];
  16983. result.y = this._pivotMatrix.m[13];
  16984. result.z = this._pivotMatrix.m[14];
  16985. this.getPivotPointToRef(result);
  16986. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16987. return this;
  16988. };
  16989. /**
  16990. * Defines the passed node as the parent of the current node.
  16991. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16992. * Returns the TransformNode.
  16993. */
  16994. TransformNode.prototype.setParent = function (node) {
  16995. if (node === null) {
  16996. var rotation = BABYLON.Tmp.Quaternion[0];
  16997. var position = BABYLON.Tmp.Vector3[0];
  16998. var scale = BABYLON.Tmp.Vector3[1];
  16999. if (this.parent && this.parent.computeWorldMatrix) {
  17000. this.parent.computeWorldMatrix(true);
  17001. }
  17002. this.computeWorldMatrix(true);
  17003. this.getWorldMatrix().decompose(scale, rotation, position);
  17004. if (this.rotationQuaternion) {
  17005. this.rotationQuaternion.copyFrom(rotation);
  17006. }
  17007. else {
  17008. rotation.toEulerAnglesToRef(this.rotation);
  17009. }
  17010. this.scaling.x = scale.x;
  17011. this.scaling.y = scale.y;
  17012. this.scaling.z = scale.z;
  17013. this.position.x = position.x;
  17014. this.position.y = position.y;
  17015. this.position.z = position.z;
  17016. }
  17017. else {
  17018. var rotation = BABYLON.Tmp.Quaternion[0];
  17019. var position = BABYLON.Tmp.Vector3[0];
  17020. var scale = BABYLON.Tmp.Vector3[1];
  17021. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17022. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17023. this.computeWorldMatrix(true);
  17024. node.computeWorldMatrix(true);
  17025. node.getWorldMatrix().invertToRef(invParentMatrix);
  17026. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17027. diffMatrix.decompose(scale, rotation, position);
  17028. if (this.rotationQuaternion) {
  17029. this.rotationQuaternion.copyFrom(rotation);
  17030. }
  17031. else {
  17032. rotation.toEulerAnglesToRef(this.rotation);
  17033. }
  17034. this.position.x = position.x;
  17035. this.position.y = position.y;
  17036. this.position.z = position.z;
  17037. this.scaling.x = scale.x;
  17038. this.scaling.y = scale.y;
  17039. this.scaling.z = scale.z;
  17040. }
  17041. this.parent = node;
  17042. return this;
  17043. };
  17044. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17045. get: function () {
  17046. return this._nonUniformScaling;
  17047. },
  17048. enumerable: true,
  17049. configurable: true
  17050. });
  17051. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17052. if (this._nonUniformScaling === value) {
  17053. return false;
  17054. }
  17055. this._nonUniformScaling = true;
  17056. return true;
  17057. };
  17058. /**
  17059. * Attach the current TransformNode to another TransformNode associated with a bone
  17060. * @param bone Bone affecting the TransformNode
  17061. * @param affectedTransformNode TransformNode associated with the bone
  17062. */
  17063. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17064. this._transformToBoneReferal = affectedTransformNode;
  17065. this.parent = bone;
  17066. if (bone.getWorldMatrix().determinant() < 0) {
  17067. this.scalingDeterminant *= -1;
  17068. }
  17069. return this;
  17070. };
  17071. TransformNode.prototype.detachFromBone = function () {
  17072. if (!this.parent) {
  17073. return this;
  17074. }
  17075. if (this.parent.getWorldMatrix().determinant() < 0) {
  17076. this.scalingDeterminant *= -1;
  17077. }
  17078. this._transformToBoneReferal = null;
  17079. this.parent = null;
  17080. return this;
  17081. };
  17082. /**
  17083. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17084. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17085. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17086. * The passed axis is also normalized.
  17087. * Returns the AbstractMesh.
  17088. */
  17089. TransformNode.prototype.rotate = function (axis, amount, space) {
  17090. axis.normalize();
  17091. if (!this.rotationQuaternion) {
  17092. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17093. this.rotation = BABYLON.Vector3.Zero();
  17094. }
  17095. var rotationQuaternion;
  17096. if (!space || space === BABYLON.Space.LOCAL) {
  17097. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17098. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17099. }
  17100. else {
  17101. if (this.parent) {
  17102. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17103. invertParentWorldMatrix.invert();
  17104. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17105. }
  17106. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17107. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17108. }
  17109. return this;
  17110. };
  17111. /**
  17112. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17113. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17114. * The passed axis is also normalized.
  17115. * Returns the AbstractMesh.
  17116. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17117. */
  17118. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17119. axis.normalize();
  17120. if (!this.rotationQuaternion) {
  17121. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17122. this.rotation.copyFromFloats(0, 0, 0);
  17123. }
  17124. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17125. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17126. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17127. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17128. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17129. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17130. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17131. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17132. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17133. return this;
  17134. };
  17135. /**
  17136. * Translates the mesh along the axis vector for the passed distance in the given space.
  17137. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17138. * Returns the AbstractMesh.
  17139. */
  17140. TransformNode.prototype.translate = function (axis, distance, space) {
  17141. var displacementVector = axis.scale(distance);
  17142. if (!space || space === BABYLON.Space.LOCAL) {
  17143. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17144. this.setPositionWithLocalVector(tempV3);
  17145. }
  17146. else {
  17147. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17148. }
  17149. return this;
  17150. };
  17151. /**
  17152. * Adds a rotation step to the mesh current rotation.
  17153. * x, y, z are Euler angles expressed in radians.
  17154. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17155. * This means this rotation is made in the mesh local space only.
  17156. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17157. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17158. * ```javascript
  17159. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17160. * ```
  17161. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17162. * 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.
  17163. * Returns the AbstractMesh.
  17164. */
  17165. TransformNode.prototype.addRotation = function (x, y, z) {
  17166. var rotationQuaternion;
  17167. if (this.rotationQuaternion) {
  17168. rotationQuaternion = this.rotationQuaternion;
  17169. }
  17170. else {
  17171. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17172. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17173. }
  17174. var accumulation = BABYLON.Tmp.Quaternion[0];
  17175. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17176. rotationQuaternion.multiplyInPlace(accumulation);
  17177. if (!this.rotationQuaternion) {
  17178. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17179. }
  17180. return this;
  17181. };
  17182. /**
  17183. * Computes the mesh World matrix and returns it.
  17184. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17185. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17186. * If the parameter `force`is set to `true`, the actual computation is done.
  17187. * Returns the mesh World Matrix.
  17188. */
  17189. TransformNode.prototype.computeWorldMatrix = function (force) {
  17190. if (this._isWorldMatrixFrozen) {
  17191. return this._worldMatrix;
  17192. }
  17193. if (!force && this.isSynchronized(true)) {
  17194. return this._worldMatrix;
  17195. }
  17196. this._cache.position.copyFrom(this.position);
  17197. this._cache.scaling.copyFrom(this.scaling);
  17198. this._cache.pivotMatrixUpdated = false;
  17199. this._cache.billboardMode = this.billboardMode;
  17200. this._currentRenderId = this.getScene().getRenderId();
  17201. this._isDirty = false;
  17202. // Scaling
  17203. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17204. // Rotation
  17205. //rotate, if quaternion is set and rotation was used
  17206. if (this.rotationQuaternion) {
  17207. var len = this.rotation.length();
  17208. if (len) {
  17209. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17210. this.rotation.copyFromFloats(0, 0, 0);
  17211. }
  17212. }
  17213. if (this.rotationQuaternion) {
  17214. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17215. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17216. }
  17217. else {
  17218. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17219. this._cache.rotation.copyFrom(this.rotation);
  17220. }
  17221. // Translation
  17222. var camera = this.getScene().activeCamera;
  17223. if (this.infiniteDistance && !this.parent && camera) {
  17224. var cameraWorldMatrix = camera.getWorldMatrix();
  17225. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17226. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17227. }
  17228. else {
  17229. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17230. }
  17231. // Composing transformations
  17232. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17233. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17234. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17235. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17236. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17237. // Need to decompose each rotation here
  17238. var currentPosition = BABYLON.Tmp.Vector3[3];
  17239. if (this.parent && this.parent.getWorldMatrix) {
  17240. if (this._transformToBoneReferal) {
  17241. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17242. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17243. }
  17244. else {
  17245. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17246. }
  17247. }
  17248. else {
  17249. currentPosition.copyFrom(this.position);
  17250. }
  17251. currentPosition.subtractInPlace(camera.globalPosition);
  17252. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17253. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17254. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17255. }
  17256. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17257. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17258. }
  17259. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17260. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17261. }
  17262. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17263. }
  17264. else {
  17265. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17266. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17267. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17268. }
  17269. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17270. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17271. }
  17272. // Local world
  17273. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17274. // Parent
  17275. if (this.parent && this.parent.getWorldMatrix) {
  17276. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17277. if (this._transformToBoneReferal) {
  17278. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17279. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17280. }
  17281. else {
  17282. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17283. }
  17284. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17285. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17286. this._worldMatrix.copyFrom(this._localWorld);
  17287. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17288. }
  17289. else {
  17290. if (this._transformToBoneReferal) {
  17291. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17292. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17293. }
  17294. else {
  17295. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17296. }
  17297. }
  17298. this._markSyncedWithParent();
  17299. }
  17300. else {
  17301. this._worldMatrix.copyFrom(this._localWorld);
  17302. }
  17303. // Post multiply inverse of pivotMatrix
  17304. if (this._postMultiplyPivotMatrix) {
  17305. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17306. }
  17307. // Normal matrix
  17308. if (this.scaling.isNonUniform) {
  17309. this._updateNonUniformScalingState(true);
  17310. }
  17311. else if (this.parent && this.parent._nonUniformScaling) {
  17312. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17313. }
  17314. else {
  17315. this._updateNonUniformScalingState(false);
  17316. }
  17317. this._afterComputeWorldMatrix();
  17318. // Absolute position
  17319. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17320. // Callbacks
  17321. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17322. if (!this._poseMatrix) {
  17323. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17324. }
  17325. // Cache the determinant
  17326. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17327. return this._worldMatrix;
  17328. };
  17329. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17330. };
  17331. /**
  17332. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17333. * @param func: callback function to add
  17334. *
  17335. * Returns the TransformNode.
  17336. */
  17337. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17338. this.onAfterWorldMatrixUpdateObservable.add(func);
  17339. return this;
  17340. };
  17341. /**
  17342. * Removes a registered callback function.
  17343. * Returns the TransformNode.
  17344. */
  17345. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17346. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17347. return this;
  17348. };
  17349. /**
  17350. * Clone the current transform node
  17351. * Returns the new transform node
  17352. * @param name Name of the new clone
  17353. * @param newParent New parent for the clone
  17354. * @param doNotCloneChildren Do not clone children hierarchy
  17355. */
  17356. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17357. var _this = this;
  17358. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17359. result.name = name;
  17360. result.id = name;
  17361. if (newParent) {
  17362. result.parent = newParent;
  17363. }
  17364. if (!doNotCloneChildren) {
  17365. // Children
  17366. var directDescendants = this.getDescendants(true);
  17367. for (var index = 0; index < directDescendants.length; index++) {
  17368. var child = directDescendants[index];
  17369. if (child.clone) {
  17370. child.clone(name + "." + child.name, result);
  17371. }
  17372. }
  17373. }
  17374. return result;
  17375. };
  17376. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17377. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17378. serializationObject.type = this.getClassName();
  17379. // Parent
  17380. if (this.parent) {
  17381. serializationObject.parentId = this.parent.id;
  17382. }
  17383. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17384. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17385. }
  17386. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17387. serializationObject.isEnabled = this.isEnabled();
  17388. // Parent
  17389. if (this.parent) {
  17390. serializationObject.parentId = this.parent.id;
  17391. }
  17392. return serializationObject;
  17393. };
  17394. // Statics
  17395. /**
  17396. * Returns a new TransformNode object parsed from the source provided.
  17397. * The parameter `parsedMesh` is the source.
  17398. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17399. */
  17400. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17401. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17402. if (BABYLON.Tags) {
  17403. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17404. }
  17405. if (parsedTransformNode.localMatrix) {
  17406. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17407. }
  17408. else if (parsedTransformNode.pivotMatrix) {
  17409. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17410. }
  17411. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17412. // Parent
  17413. if (parsedTransformNode.parentId) {
  17414. transformNode._waitingParentId = parsedTransformNode.parentId;
  17415. }
  17416. return transformNode;
  17417. };
  17418. /**
  17419. * Releases resources associated with this transform node.
  17420. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17421. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17422. */
  17423. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17424. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17425. // Animations
  17426. this.getScene().stopAnimation(this);
  17427. // Remove from scene
  17428. this.getScene().removeTransformNode(this);
  17429. this.onAfterWorldMatrixUpdateObservable.clear();
  17430. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17431. };
  17432. // Statics
  17433. TransformNode.BILLBOARDMODE_NONE = 0;
  17434. TransformNode.BILLBOARDMODE_X = 1;
  17435. TransformNode.BILLBOARDMODE_Y = 2;
  17436. TransformNode.BILLBOARDMODE_Z = 4;
  17437. TransformNode.BILLBOARDMODE_ALL = 7;
  17438. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17439. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17440. __decorate([
  17441. BABYLON.serializeAsVector3()
  17442. ], TransformNode.prototype, "_rotation", void 0);
  17443. __decorate([
  17444. BABYLON.serializeAsQuaternion()
  17445. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17446. __decorate([
  17447. BABYLON.serializeAsVector3()
  17448. ], TransformNode.prototype, "_scaling", void 0);
  17449. __decorate([
  17450. BABYLON.serialize()
  17451. ], TransformNode.prototype, "billboardMode", void 0);
  17452. __decorate([
  17453. BABYLON.serialize()
  17454. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17455. __decorate([
  17456. BABYLON.serialize()
  17457. ], TransformNode.prototype, "infiniteDistance", void 0);
  17458. __decorate([
  17459. BABYLON.serializeAsVector3()
  17460. ], TransformNode.prototype, "position", void 0);
  17461. return TransformNode;
  17462. }(BABYLON.Node));
  17463. BABYLON.TransformNode = TransformNode;
  17464. })(BABYLON || (BABYLON = {}));
  17465. //# sourceMappingURL=babylon.transformNode.js.map
  17466. "use strict";
  17467. var BABYLON;
  17468. (function (BABYLON) {
  17469. var AbstractMesh = /** @class */ (function (_super) {
  17470. __extends(AbstractMesh, _super);
  17471. // Constructor
  17472. function AbstractMesh(name, scene) {
  17473. if (scene === void 0) { scene = null; }
  17474. var _this = _super.call(this, name, scene, false) || this;
  17475. _this._facetNb = 0; // facet number
  17476. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17477. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17478. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17479. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17480. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17481. _this._subDiv = {
  17482. max: 1,
  17483. X: 1,
  17484. Y: 1,
  17485. Z: 1
  17486. };
  17487. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17488. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17489. // Events
  17490. /**
  17491. * An event triggered when this mesh collides with another one
  17492. * @type {BABYLON.Observable}
  17493. */
  17494. _this.onCollideObservable = new BABYLON.Observable();
  17495. /**
  17496. * An event triggered when the collision's position changes
  17497. * @type {BABYLON.Observable}
  17498. */
  17499. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17500. /**
  17501. * An event triggered when material is changed
  17502. * @type {BABYLON.Observable}
  17503. */
  17504. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17505. // Properties
  17506. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17507. /**
  17508. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17509. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17510. * or
  17511. * 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.
  17512. * for more info check WebGl documentations
  17513. */
  17514. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17515. /**
  17516. * 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:
  17517. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17518. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17519. * 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.
  17520. */
  17521. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17522. /**
  17523. * 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.
  17524. * The default value is -1 which means don't break the query and wait till the result.
  17525. */
  17526. _this.occlusionRetryCount = -1;
  17527. _this._occlusionInternalRetryCounter = 0;
  17528. _this._isOccluded = false;
  17529. _this._isOcclusionQueryInProgress = false;
  17530. _this._visibility = 1.0;
  17531. _this.alphaIndex = Number.MAX_VALUE;
  17532. _this.isVisible = true;
  17533. _this.isPickable = true;
  17534. _this.showBoundingBox = false;
  17535. _this.showSubMeshesBoundingBox = false;
  17536. _this.isBlocker = false;
  17537. _this.enablePointerMoveEvents = false;
  17538. _this.renderingGroupId = 0;
  17539. _this._receiveShadows = false;
  17540. _this.renderOutline = false;
  17541. _this.outlineColor = BABYLON.Color3.Red();
  17542. _this.outlineWidth = 0.02;
  17543. _this.renderOverlay = false;
  17544. _this.overlayColor = BABYLON.Color3.Red();
  17545. _this.overlayAlpha = 0.5;
  17546. _this._hasVertexAlpha = false;
  17547. _this._useVertexColors = true;
  17548. _this._computeBonesUsingShaders = true;
  17549. _this._numBoneInfluencers = 4;
  17550. _this._applyFog = true;
  17551. _this.useOctreeForRenderingSelection = true;
  17552. _this.useOctreeForPicking = true;
  17553. _this.useOctreeForCollisions = true;
  17554. _this._layerMask = 0x0FFFFFFF;
  17555. /**
  17556. * True if the mesh must be rendered in any case.
  17557. */
  17558. _this.alwaysSelectAsActiveMesh = false;
  17559. /**
  17560. * This scene's action manager
  17561. * @type {BABYLON.ActionManager}
  17562. */
  17563. _this.actionManager = null;
  17564. // Physics
  17565. _this.physicsImpostor = null;
  17566. // Collisions
  17567. _this._checkCollisions = false;
  17568. _this._collisionMask = -1;
  17569. _this._collisionGroup = -1;
  17570. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17571. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17572. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17573. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17574. // Edges
  17575. _this.edgesWidth = 1;
  17576. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17577. // Cache
  17578. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17579. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17580. _this._renderId = 0;
  17581. _this._intersectionsInProgress = new Array();
  17582. _this._unIndexed = false;
  17583. _this._lightSources = new Array();
  17584. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17585. if (collidedMesh === void 0) { collidedMesh = null; }
  17586. //TODO move this to the collision coordinator!
  17587. if (_this.getScene().workerCollisions)
  17588. newPosition.multiplyInPlace(_this._collider._radius);
  17589. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17590. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17591. _this.position.addInPlace(_this._diffPositionForCollisions);
  17592. }
  17593. if (collidedMesh) {
  17594. _this.onCollideObservable.notifyObservers(collidedMesh);
  17595. }
  17596. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17597. };
  17598. _this.getScene().addMesh(_this);
  17599. _this._resyncLightSources();
  17600. return _this;
  17601. }
  17602. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17603. get: function () {
  17604. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17605. },
  17606. enumerable: true,
  17607. configurable: true
  17608. });
  17609. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17610. get: function () {
  17611. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17612. },
  17613. enumerable: true,
  17614. configurable: true
  17615. });
  17616. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17617. get: function () {
  17618. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17619. },
  17620. enumerable: true,
  17621. configurable: true
  17622. });
  17623. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17624. get: function () {
  17625. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17626. },
  17627. enumerable: true,
  17628. configurable: true
  17629. });
  17630. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17631. get: function () {
  17632. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17633. },
  17634. enumerable: true,
  17635. configurable: true
  17636. });
  17637. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17638. /**
  17639. * Read-only : the number of facets in the mesh
  17640. */
  17641. get: function () {
  17642. return this._facetNb;
  17643. },
  17644. enumerable: true,
  17645. configurable: true
  17646. });
  17647. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17648. /**
  17649. * The number (integer) of subdivisions per axis in the partioning space
  17650. */
  17651. get: function () {
  17652. return this._partitioningSubdivisions;
  17653. },
  17654. set: function (nb) {
  17655. this._partitioningSubdivisions = nb;
  17656. },
  17657. enumerable: true,
  17658. configurable: true
  17659. });
  17660. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17661. /**
  17662. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17663. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17664. */
  17665. get: function () {
  17666. return this._partitioningBBoxRatio;
  17667. },
  17668. set: function (ratio) {
  17669. this._partitioningBBoxRatio = ratio;
  17670. },
  17671. enumerable: true,
  17672. configurable: true
  17673. });
  17674. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17675. /**
  17676. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17677. * Works only for updatable meshes.
  17678. * Doesn't work with multi-materials.
  17679. */
  17680. get: function () {
  17681. return this._facetDepthSort;
  17682. },
  17683. set: function (sort) {
  17684. this._facetDepthSort = sort;
  17685. },
  17686. enumerable: true,
  17687. configurable: true
  17688. });
  17689. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17690. /**
  17691. * The location (Vector3) where the facet depth sort must be computed from.
  17692. * By default, the active camera position.
  17693. * Used only when facet depth sort is enabled.
  17694. */
  17695. get: function () {
  17696. return this._facetDepthSortFrom;
  17697. },
  17698. set: function (location) {
  17699. this._facetDepthSortFrom = location;
  17700. },
  17701. enumerable: true,
  17702. configurable: true
  17703. });
  17704. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17705. /**
  17706. * Read-only boolean : is the feature facetData enabled ?
  17707. */
  17708. get: function () {
  17709. return this._facetDataEnabled;
  17710. },
  17711. enumerable: true,
  17712. configurable: true
  17713. });
  17714. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17715. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17716. return false;
  17717. }
  17718. this._markSubMeshesAsMiscDirty();
  17719. return true;
  17720. };
  17721. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17722. set: function (callback) {
  17723. if (this._onCollideObserver) {
  17724. this.onCollideObservable.remove(this._onCollideObserver);
  17725. }
  17726. this._onCollideObserver = this.onCollideObservable.add(callback);
  17727. },
  17728. enumerable: true,
  17729. configurable: true
  17730. });
  17731. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17732. set: function (callback) {
  17733. if (this._onCollisionPositionChangeObserver) {
  17734. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17735. }
  17736. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17737. },
  17738. enumerable: true,
  17739. configurable: true
  17740. });
  17741. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17742. /**
  17743. * 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.
  17744. */
  17745. get: function () {
  17746. return this._isOccluded;
  17747. },
  17748. set: function (value) {
  17749. this._isOccluded = value;
  17750. },
  17751. enumerable: true,
  17752. configurable: true
  17753. });
  17754. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17755. /**
  17756. * Flag to check the progress status of the query
  17757. */
  17758. get: function () {
  17759. return this._isOcclusionQueryInProgress;
  17760. },
  17761. enumerable: true,
  17762. configurable: true
  17763. });
  17764. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17765. /**
  17766. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17767. */
  17768. get: function () {
  17769. return this._visibility;
  17770. },
  17771. /**
  17772. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17773. */
  17774. set: function (value) {
  17775. if (this._visibility === value) {
  17776. return;
  17777. }
  17778. this._visibility = value;
  17779. this._markSubMeshesAsMiscDirty();
  17780. },
  17781. enumerable: true,
  17782. configurable: true
  17783. });
  17784. Object.defineProperty(AbstractMesh.prototype, "material", {
  17785. get: function () {
  17786. return this._material;
  17787. },
  17788. set: function (value) {
  17789. if (this._material === value) {
  17790. return;
  17791. }
  17792. this._material = value;
  17793. if (this.onMaterialChangedObservable.hasObservers) {
  17794. this.onMaterialChangedObservable.notifyObservers(this);
  17795. }
  17796. if (!this.subMeshes) {
  17797. return;
  17798. }
  17799. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17800. var subMesh = _a[_i];
  17801. subMesh.setEffect(null);
  17802. }
  17803. },
  17804. enumerable: true,
  17805. configurable: true
  17806. });
  17807. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17808. get: function () {
  17809. return this._receiveShadows;
  17810. },
  17811. set: function (value) {
  17812. if (this._receiveShadows === value) {
  17813. return;
  17814. }
  17815. this._receiveShadows = value;
  17816. this._markSubMeshesAsLightDirty();
  17817. },
  17818. enumerable: true,
  17819. configurable: true
  17820. });
  17821. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17822. get: function () {
  17823. return this._hasVertexAlpha;
  17824. },
  17825. set: function (value) {
  17826. if (this._hasVertexAlpha === value) {
  17827. return;
  17828. }
  17829. this._hasVertexAlpha = value;
  17830. this._markSubMeshesAsAttributesDirty();
  17831. this._markSubMeshesAsMiscDirty();
  17832. },
  17833. enumerable: true,
  17834. configurable: true
  17835. });
  17836. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17837. get: function () {
  17838. return this._useVertexColors;
  17839. },
  17840. set: function (value) {
  17841. if (this._useVertexColors === value) {
  17842. return;
  17843. }
  17844. this._useVertexColors = value;
  17845. this._markSubMeshesAsAttributesDirty();
  17846. },
  17847. enumerable: true,
  17848. configurable: true
  17849. });
  17850. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17851. get: function () {
  17852. return this._computeBonesUsingShaders;
  17853. },
  17854. set: function (value) {
  17855. if (this._computeBonesUsingShaders === value) {
  17856. return;
  17857. }
  17858. this._computeBonesUsingShaders = value;
  17859. this._markSubMeshesAsAttributesDirty();
  17860. },
  17861. enumerable: true,
  17862. configurable: true
  17863. });
  17864. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17865. get: function () {
  17866. return this._numBoneInfluencers;
  17867. },
  17868. set: function (value) {
  17869. if (this._numBoneInfluencers === value) {
  17870. return;
  17871. }
  17872. this._numBoneInfluencers = value;
  17873. this._markSubMeshesAsAttributesDirty();
  17874. },
  17875. enumerable: true,
  17876. configurable: true
  17877. });
  17878. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17879. get: function () {
  17880. return this._applyFog;
  17881. },
  17882. set: function (value) {
  17883. if (this._applyFog === value) {
  17884. return;
  17885. }
  17886. this._applyFog = value;
  17887. this._markSubMeshesAsMiscDirty();
  17888. },
  17889. enumerable: true,
  17890. configurable: true
  17891. });
  17892. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17893. get: function () {
  17894. return this._layerMask;
  17895. },
  17896. set: function (value) {
  17897. if (value === this._layerMask) {
  17898. return;
  17899. }
  17900. this._layerMask = value;
  17901. this._resyncLightSources();
  17902. },
  17903. enumerable: true,
  17904. configurable: true
  17905. });
  17906. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17907. get: function () {
  17908. return this._collisionMask;
  17909. },
  17910. set: function (mask) {
  17911. this._collisionMask = !isNaN(mask) ? mask : -1;
  17912. },
  17913. enumerable: true,
  17914. configurable: true
  17915. });
  17916. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17917. get: function () {
  17918. return this._collisionGroup;
  17919. },
  17920. set: function (mask) {
  17921. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17922. },
  17923. enumerable: true,
  17924. configurable: true
  17925. });
  17926. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17927. get: function () {
  17928. return null;
  17929. },
  17930. enumerable: true,
  17931. configurable: true
  17932. });
  17933. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17934. get: function () {
  17935. return this._skeleton;
  17936. },
  17937. set: function (value) {
  17938. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17939. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17940. }
  17941. if (value && value.needInitialSkinMatrix) {
  17942. value._registerMeshWithPoseMatrix(this);
  17943. }
  17944. this._skeleton = value;
  17945. if (!this._skeleton) {
  17946. this._bonesTransformMatrices = null;
  17947. }
  17948. this._markSubMeshesAsAttributesDirty();
  17949. },
  17950. enumerable: true,
  17951. configurable: true
  17952. });
  17953. /**
  17954. * Returns the string "AbstractMesh"
  17955. */
  17956. AbstractMesh.prototype.getClassName = function () {
  17957. return "AbstractMesh";
  17958. };
  17959. /**
  17960. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17961. */
  17962. AbstractMesh.prototype.toString = function (fullDetails) {
  17963. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17964. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17965. if (this._skeleton) {
  17966. ret += ", skeleton: " + this._skeleton.name;
  17967. }
  17968. if (fullDetails) {
  17969. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17970. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17971. }
  17972. return ret;
  17973. };
  17974. AbstractMesh.prototype._rebuild = function () {
  17975. if (this._occlusionQuery) {
  17976. this._occlusionQuery = null;
  17977. }
  17978. if (this._edgesRenderer) {
  17979. this._edgesRenderer._rebuild();
  17980. }
  17981. if (!this.subMeshes) {
  17982. return;
  17983. }
  17984. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17985. var subMesh = _a[_i];
  17986. subMesh._rebuild();
  17987. }
  17988. };
  17989. AbstractMesh.prototype._resyncLightSources = function () {
  17990. this._lightSources.length = 0;
  17991. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17992. var light = _a[_i];
  17993. if (!light.isEnabled()) {
  17994. continue;
  17995. }
  17996. if (light.canAffectMesh(this)) {
  17997. this._lightSources.push(light);
  17998. }
  17999. }
  18000. this._markSubMeshesAsLightDirty();
  18001. };
  18002. AbstractMesh.prototype._resyncLighSource = function (light) {
  18003. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18004. var index = this._lightSources.indexOf(light);
  18005. if (index === -1) {
  18006. if (!isIn) {
  18007. return;
  18008. }
  18009. this._lightSources.push(light);
  18010. }
  18011. else {
  18012. if (isIn) {
  18013. return;
  18014. }
  18015. this._lightSources.splice(index, 1);
  18016. }
  18017. this._markSubMeshesAsLightDirty();
  18018. };
  18019. AbstractMesh.prototype._removeLightSource = function (light) {
  18020. var index = this._lightSources.indexOf(light);
  18021. if (index === -1) {
  18022. return;
  18023. }
  18024. this._lightSources.splice(index, 1);
  18025. this._markSubMeshesAsLightDirty();
  18026. };
  18027. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18028. if (!this.subMeshes) {
  18029. return;
  18030. }
  18031. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18032. var subMesh = _a[_i];
  18033. if (subMesh._materialDefines) {
  18034. func(subMesh._materialDefines);
  18035. }
  18036. }
  18037. };
  18038. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18039. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18040. };
  18041. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18042. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18043. };
  18044. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18045. if (!this.subMeshes) {
  18046. return;
  18047. }
  18048. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18049. var subMesh = _a[_i];
  18050. var material = subMesh.getMaterial();
  18051. if (material) {
  18052. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18053. }
  18054. }
  18055. };
  18056. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18057. /**
  18058. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18059. * Default : (1.0, 1.0, 1.0)
  18060. */
  18061. get: function () {
  18062. return this._scaling;
  18063. },
  18064. /**
  18065. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18066. * Default : (1.0, 1.0, 1.0)
  18067. */
  18068. set: function (newScaling) {
  18069. this._scaling = newScaling;
  18070. if (this.physicsImpostor) {
  18071. this.physicsImpostor.forceUpdate();
  18072. }
  18073. },
  18074. enumerable: true,
  18075. configurable: true
  18076. });
  18077. // Methods
  18078. /**
  18079. * Disables the mesh edger rendering mode.
  18080. * Returns the AbstractMesh.
  18081. */
  18082. AbstractMesh.prototype.disableEdgesRendering = function () {
  18083. if (this._edgesRenderer) {
  18084. this._edgesRenderer.dispose();
  18085. this._edgesRenderer = null;
  18086. }
  18087. return this;
  18088. };
  18089. /**
  18090. * Enables the edge rendering mode on the mesh.
  18091. * This mode makes the mesh edges visible.
  18092. * Returns the AbstractMesh.
  18093. */
  18094. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18095. if (epsilon === void 0) { epsilon = 0.95; }
  18096. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18097. this.disableEdgesRendering();
  18098. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18099. return this;
  18100. };
  18101. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18102. /**
  18103. * Returns true if the mesh is blocked. Used by the class Mesh.
  18104. * Returns the boolean `false` by default.
  18105. */
  18106. get: function () {
  18107. return false;
  18108. },
  18109. enumerable: true,
  18110. configurable: true
  18111. });
  18112. /**
  18113. * Returns the mesh itself by default, used by the class Mesh.
  18114. * Returned type : AbstractMesh
  18115. */
  18116. AbstractMesh.prototype.getLOD = function (camera) {
  18117. return this;
  18118. };
  18119. /**
  18120. * Returns 0 by default, used by the class Mesh.
  18121. * Returns an integer.
  18122. */
  18123. AbstractMesh.prototype.getTotalVertices = function () {
  18124. return 0;
  18125. };
  18126. /**
  18127. * Returns null by default, used by the class Mesh.
  18128. * Returned type : integer array
  18129. */
  18130. AbstractMesh.prototype.getIndices = function () {
  18131. return null;
  18132. };
  18133. /**
  18134. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18135. * Returned type : float array or Float32Array
  18136. */
  18137. AbstractMesh.prototype.getVerticesData = function (kind) {
  18138. return null;
  18139. };
  18140. /**
  18141. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18142. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18143. * The `data` are either a numeric array either a Float32Array.
  18144. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18145. * 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).
  18146. * Note that a new underlying VertexBuffer object is created each call.
  18147. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18148. *
  18149. * Possible `kind` values :
  18150. * - BABYLON.VertexBuffer.PositionKind
  18151. * - BABYLON.VertexBuffer.UVKind
  18152. * - BABYLON.VertexBuffer.UV2Kind
  18153. * - BABYLON.VertexBuffer.UV3Kind
  18154. * - BABYLON.VertexBuffer.UV4Kind
  18155. * - BABYLON.VertexBuffer.UV5Kind
  18156. * - BABYLON.VertexBuffer.UV6Kind
  18157. * - BABYLON.VertexBuffer.ColorKind
  18158. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18159. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18160. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18161. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18162. *
  18163. * Returns the Mesh.
  18164. */
  18165. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18166. return this;
  18167. };
  18168. /**
  18169. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18170. * If the mesh has no geometry, it is simply returned as it is.
  18171. * The `data` are either a numeric array either a Float32Array.
  18172. * No new underlying VertexBuffer object is created.
  18173. * 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.
  18174. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18175. *
  18176. * Possible `kind` values :
  18177. * - BABYLON.VertexBuffer.PositionKind
  18178. * - BABYLON.VertexBuffer.UVKind
  18179. * - BABYLON.VertexBuffer.UV2Kind
  18180. * - BABYLON.VertexBuffer.UV3Kind
  18181. * - BABYLON.VertexBuffer.UV4Kind
  18182. * - BABYLON.VertexBuffer.UV5Kind
  18183. * - BABYLON.VertexBuffer.UV6Kind
  18184. * - BABYLON.VertexBuffer.ColorKind
  18185. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18186. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18187. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18188. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18189. *
  18190. * Returns the Mesh.
  18191. */
  18192. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18193. return this;
  18194. };
  18195. /**
  18196. * Sets the mesh indices.
  18197. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18198. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18199. * This method creates a new index buffer each call.
  18200. * Returns the Mesh.
  18201. */
  18202. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18203. return this;
  18204. };
  18205. /** Returns false by default, used by the class Mesh.
  18206. * Returns a boolean
  18207. */
  18208. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18209. return false;
  18210. };
  18211. /**
  18212. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18213. * Returns a BoundingInfo
  18214. */
  18215. AbstractMesh.prototype.getBoundingInfo = function () {
  18216. if (this._masterMesh) {
  18217. return this._masterMesh.getBoundingInfo();
  18218. }
  18219. if (!this._boundingInfo) {
  18220. // this._boundingInfo is being created here
  18221. this._updateBoundingInfo();
  18222. }
  18223. // cannot be null.
  18224. return this._boundingInfo;
  18225. };
  18226. /**
  18227. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18228. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18229. */
  18230. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18231. if (includeDescendants === void 0) { includeDescendants = true; }
  18232. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18233. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18234. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18235. if (maxDimension === 0) {
  18236. return this;
  18237. }
  18238. var scale = 1 / maxDimension;
  18239. this.scaling.scaleInPlace(scale);
  18240. return this;
  18241. };
  18242. /**
  18243. * Sets a mesh new object BoundingInfo.
  18244. * Returns the AbstractMesh.
  18245. */
  18246. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18247. this._boundingInfo = boundingInfo;
  18248. return this;
  18249. };
  18250. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18251. get: function () {
  18252. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18253. },
  18254. enumerable: true,
  18255. configurable: true
  18256. });
  18257. AbstractMesh.prototype._preActivate = function () {
  18258. };
  18259. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18260. };
  18261. AbstractMesh.prototype._activate = function (renderId) {
  18262. this._renderId = renderId;
  18263. };
  18264. /**
  18265. * Returns the latest update of the World matrix
  18266. * Returns a Matrix.
  18267. */
  18268. AbstractMesh.prototype.getWorldMatrix = function () {
  18269. if (this._masterMesh) {
  18270. return this._masterMesh.getWorldMatrix();
  18271. }
  18272. return _super.prototype.getWorldMatrix.call(this);
  18273. };
  18274. /**
  18275. * Returns the latest update of the World matrix determinant.
  18276. */
  18277. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18278. if (this._masterMesh) {
  18279. return this._masterMesh._getWorldMatrixDeterminant();
  18280. }
  18281. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18282. };
  18283. // ================================== Point of View Movement =================================
  18284. /**
  18285. * Perform relative position change from the point of view of behind the front of the mesh.
  18286. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18287. * Supports definition of mesh facing forward or backward.
  18288. * @param {number} amountRight
  18289. * @param {number} amountUp
  18290. * @param {number} amountForward
  18291. *
  18292. * Returns the AbstractMesh.
  18293. */
  18294. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18295. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18296. return this;
  18297. };
  18298. /**
  18299. * Calculate relative position change from the point of view of behind the front of the mesh.
  18300. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18301. * Supports definition of mesh facing forward or backward.
  18302. * @param {number} amountRight
  18303. * @param {number} amountUp
  18304. * @param {number} amountForward
  18305. *
  18306. * Returns a new Vector3.
  18307. */
  18308. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18309. var rotMatrix = new BABYLON.Matrix();
  18310. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18311. rotQuaternion.toRotationMatrix(rotMatrix);
  18312. var translationDelta = BABYLON.Vector3.Zero();
  18313. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18314. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18315. return translationDelta;
  18316. };
  18317. // ================================== Point of View Rotation =================================
  18318. /**
  18319. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18320. * Supports definition of mesh facing forward or backward.
  18321. * @param {number} flipBack
  18322. * @param {number} twirlClockwise
  18323. * @param {number} tiltRight
  18324. *
  18325. * Returns the AbstractMesh.
  18326. */
  18327. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18328. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18329. return this;
  18330. };
  18331. /**
  18332. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18333. * Supports definition of mesh facing forward or backward.
  18334. * @param {number} flipBack
  18335. * @param {number} twirlClockwise
  18336. * @param {number} tiltRight
  18337. *
  18338. * Returns a new Vector3.
  18339. */
  18340. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18341. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18342. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18343. };
  18344. /**
  18345. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18346. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18347. */
  18348. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18349. if (includeDescendants === void 0) { includeDescendants = true; }
  18350. this.computeWorldMatrix(true);
  18351. var min;
  18352. var max;
  18353. var boundingInfo = this.getBoundingInfo();
  18354. if (!this.subMeshes) {
  18355. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18356. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18357. }
  18358. else {
  18359. min = boundingInfo.boundingBox.minimumWorld;
  18360. max = boundingInfo.boundingBox.maximumWorld;
  18361. }
  18362. if (includeDescendants) {
  18363. var descendants = this.getDescendants(false);
  18364. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18365. var descendant = descendants_1[_i];
  18366. var childMesh = descendant;
  18367. childMesh.computeWorldMatrix(true);
  18368. //make sure we have the needed params to get mix and max
  18369. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18370. continue;
  18371. }
  18372. var childBoundingInfo = childMesh.getBoundingInfo();
  18373. var boundingBox = childBoundingInfo.boundingBox;
  18374. var minBox = boundingBox.minimumWorld;
  18375. var maxBox = boundingBox.maximumWorld;
  18376. BABYLON.Tools.CheckExtends(minBox, min, max);
  18377. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18378. }
  18379. }
  18380. return {
  18381. min: min,
  18382. max: max
  18383. };
  18384. };
  18385. /**
  18386. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18387. * Returns the AbstractMesh.
  18388. */
  18389. AbstractMesh.prototype._updateBoundingInfo = function () {
  18390. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18391. this._boundingInfo.update(this.worldMatrixFromCache);
  18392. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18393. return this;
  18394. };
  18395. /**
  18396. * Update a mesh's children BoundingInfo objects only.
  18397. * Returns the AbstractMesh.
  18398. */
  18399. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18400. if (!this.subMeshes) {
  18401. return this;
  18402. }
  18403. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18404. var subMesh = this.subMeshes[subIndex];
  18405. if (!subMesh.IsGlobal) {
  18406. subMesh.updateBoundingInfo(matrix);
  18407. }
  18408. }
  18409. return this;
  18410. };
  18411. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18412. // Bounding info
  18413. this._updateBoundingInfo();
  18414. };
  18415. /**
  18416. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18417. * A mesh is in the frustum if its bounding box intersects the frustum.
  18418. * Boolean returned.
  18419. */
  18420. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18421. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18422. };
  18423. /**
  18424. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18425. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18426. * Boolean returned.
  18427. */
  18428. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18429. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18430. ;
  18431. };
  18432. /**
  18433. * True if the mesh intersects another mesh or a SolidParticle object.
  18434. * 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)
  18435. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18436. * Returns a boolean.
  18437. */
  18438. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18439. if (precise === void 0) { precise = false; }
  18440. if (!this._boundingInfo || !mesh._boundingInfo) {
  18441. return false;
  18442. }
  18443. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18444. return true;
  18445. }
  18446. if (includeDescendants) {
  18447. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18448. var child = _a[_i];
  18449. if (child.intersectsMesh(mesh, precise, true)) {
  18450. return true;
  18451. }
  18452. }
  18453. }
  18454. return false;
  18455. };
  18456. /**
  18457. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18458. * Returns a boolean.
  18459. */
  18460. AbstractMesh.prototype.intersectsPoint = function (point) {
  18461. if (!this._boundingInfo) {
  18462. return false;
  18463. }
  18464. return this._boundingInfo.intersectsPoint(point);
  18465. };
  18466. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18467. return this.physicsImpostor;
  18468. };
  18469. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18470. if (camera === void 0) { camera = null; }
  18471. if (!camera) {
  18472. camera = this.getScene().activeCamera;
  18473. }
  18474. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18475. };
  18476. /**
  18477. * Returns the distance from the mesh to the active camera.
  18478. * Returns a float.
  18479. */
  18480. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18481. if (camera === void 0) { camera = null; }
  18482. if (!camera) {
  18483. camera = this.getScene().activeCamera;
  18484. }
  18485. return this.absolutePosition.subtract(camera.position).length();
  18486. };
  18487. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18488. if (!this.physicsImpostor) {
  18489. return this;
  18490. }
  18491. this.physicsImpostor.applyImpulse(force, contactPoint);
  18492. return this;
  18493. };
  18494. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18495. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18496. return this;
  18497. }
  18498. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18499. mainPivot: pivot1,
  18500. connectedPivot: pivot2,
  18501. nativeParams: options
  18502. });
  18503. return this;
  18504. };
  18505. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18506. // Collisions
  18507. /**
  18508. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18509. * Default `false`.
  18510. */
  18511. get: function () {
  18512. return this._checkCollisions;
  18513. },
  18514. set: function (collisionEnabled) {
  18515. this._checkCollisions = collisionEnabled;
  18516. if (this.getScene().workerCollisions) {
  18517. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18518. }
  18519. },
  18520. enumerable: true,
  18521. configurable: true
  18522. });
  18523. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18524. /**
  18525. * Gets Collider object used to compute collisions (not physics)
  18526. */
  18527. get: function () {
  18528. return this._collider;
  18529. },
  18530. enumerable: true,
  18531. configurable: true
  18532. });
  18533. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18534. var globalPosition = this.getAbsolutePosition();
  18535. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18536. if (!this._collider) {
  18537. this._collider = new BABYLON.Collider();
  18538. }
  18539. this._collider._radius = this.ellipsoid;
  18540. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18541. return this;
  18542. };
  18543. // Submeshes octree
  18544. /**
  18545. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18546. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18547. * Returns an Octree of submeshes.
  18548. */
  18549. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18550. if (maxCapacity === void 0) { maxCapacity = 64; }
  18551. if (maxDepth === void 0) { maxDepth = 2; }
  18552. if (!this._submeshesOctree) {
  18553. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18554. }
  18555. this.computeWorldMatrix(true);
  18556. var boundingInfo = this.getBoundingInfo();
  18557. // Update octree
  18558. var bbox = boundingInfo.boundingBox;
  18559. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18560. return this._submeshesOctree;
  18561. };
  18562. // Collisions
  18563. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18564. this._generatePointsArray();
  18565. if (!this._positions) {
  18566. return this;
  18567. }
  18568. // Transformation
  18569. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18570. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18571. subMesh._lastColliderWorldVertices = [];
  18572. subMesh._trianglePlanes = [];
  18573. var start = subMesh.verticesStart;
  18574. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18575. for (var i = start; i < end; i++) {
  18576. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18577. }
  18578. }
  18579. // Collide
  18580. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18581. if (collider.collisionFound) {
  18582. collider.collidedMesh = this;
  18583. }
  18584. return this;
  18585. };
  18586. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18587. var subMeshes;
  18588. var len;
  18589. // Octrees
  18590. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18591. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18592. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18593. len = intersections.length;
  18594. subMeshes = intersections.data;
  18595. }
  18596. else {
  18597. subMeshes = this.subMeshes;
  18598. len = subMeshes.length;
  18599. }
  18600. for (var index = 0; index < len; index++) {
  18601. var subMesh = subMeshes[index];
  18602. // Bounding test
  18603. if (len > 1 && !subMesh._checkCollision(collider))
  18604. continue;
  18605. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18606. }
  18607. return this;
  18608. };
  18609. AbstractMesh.prototype._checkCollision = function (collider) {
  18610. // Bounding box test
  18611. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18612. return this;
  18613. // Transformation matrix
  18614. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18615. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18616. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18617. return this;
  18618. };
  18619. // Picking
  18620. AbstractMesh.prototype._generatePointsArray = function () {
  18621. return false;
  18622. };
  18623. /**
  18624. * Checks if the passed Ray intersects with the mesh.
  18625. * Returns an object PickingInfo.
  18626. */
  18627. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18628. var pickingInfo = new BABYLON.PickingInfo();
  18629. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18630. return pickingInfo;
  18631. }
  18632. if (!this._generatePointsArray()) {
  18633. return pickingInfo;
  18634. }
  18635. var intersectInfo = null;
  18636. // Octrees
  18637. var subMeshes;
  18638. var len;
  18639. if (this._submeshesOctree && this.useOctreeForPicking) {
  18640. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18641. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18642. len = intersections.length;
  18643. subMeshes = intersections.data;
  18644. }
  18645. else {
  18646. subMeshes = this.subMeshes;
  18647. len = subMeshes.length;
  18648. }
  18649. for (var index = 0; index < len; index++) {
  18650. var subMesh = subMeshes[index];
  18651. // Bounding test
  18652. if (len > 1 && !subMesh.canIntersects(ray))
  18653. continue;
  18654. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18655. if (currentIntersectInfo) {
  18656. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18657. intersectInfo = currentIntersectInfo;
  18658. intersectInfo.subMeshId = index;
  18659. if (fastCheck) {
  18660. break;
  18661. }
  18662. }
  18663. }
  18664. }
  18665. if (intersectInfo) {
  18666. // Get picked point
  18667. var world = this.getWorldMatrix();
  18668. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18669. var direction = ray.direction.clone();
  18670. direction = direction.scale(intersectInfo.distance);
  18671. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18672. var pickedPoint = worldOrigin.add(worldDirection);
  18673. // Return result
  18674. pickingInfo.hit = true;
  18675. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18676. pickingInfo.pickedPoint = pickedPoint;
  18677. pickingInfo.pickedMesh = this;
  18678. pickingInfo.bu = intersectInfo.bu || 0;
  18679. pickingInfo.bv = intersectInfo.bv || 0;
  18680. pickingInfo.faceId = intersectInfo.faceId;
  18681. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18682. return pickingInfo;
  18683. }
  18684. return pickingInfo;
  18685. };
  18686. /**
  18687. * Clones the mesh, used by the class Mesh.
  18688. * Just returns `null` for an AbstractMesh.
  18689. */
  18690. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18691. return null;
  18692. };
  18693. /**
  18694. * Disposes all the mesh submeshes.
  18695. * Returns the AbstractMesh.
  18696. */
  18697. AbstractMesh.prototype.releaseSubMeshes = function () {
  18698. if (this.subMeshes) {
  18699. while (this.subMeshes.length) {
  18700. this.subMeshes[0].dispose();
  18701. }
  18702. }
  18703. else {
  18704. this.subMeshes = new Array();
  18705. }
  18706. return this;
  18707. };
  18708. /**
  18709. * Releases resources associated with this abstract mesh.
  18710. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18711. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18712. */
  18713. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18714. var _this = this;
  18715. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18716. var index;
  18717. // Smart Array Retainers.
  18718. this.getScene().freeActiveMeshes();
  18719. this.getScene().freeRenderingGroups();
  18720. // Action manager
  18721. if (this.actionManager !== undefined && this.actionManager !== null) {
  18722. this.actionManager.dispose();
  18723. this.actionManager = null;
  18724. }
  18725. // Skeleton
  18726. this._skeleton = null;
  18727. // Physics
  18728. if (this.physicsImpostor) {
  18729. this.physicsImpostor.dispose();
  18730. }
  18731. // Intersections in progress
  18732. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18733. var other = this._intersectionsInProgress[index];
  18734. var pos = other._intersectionsInProgress.indexOf(this);
  18735. other._intersectionsInProgress.splice(pos, 1);
  18736. }
  18737. this._intersectionsInProgress = [];
  18738. // Lights
  18739. var lights = this.getScene().lights;
  18740. lights.forEach(function (light) {
  18741. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18742. if (meshIndex !== -1) {
  18743. light.includedOnlyMeshes.splice(meshIndex, 1);
  18744. }
  18745. meshIndex = light.excludedMeshes.indexOf(_this);
  18746. if (meshIndex !== -1) {
  18747. light.excludedMeshes.splice(meshIndex, 1);
  18748. }
  18749. // Shadow generators
  18750. var generator = light.getShadowGenerator();
  18751. if (generator) {
  18752. var shadowMap = generator.getShadowMap();
  18753. if (shadowMap && shadowMap.renderList) {
  18754. meshIndex = shadowMap.renderList.indexOf(_this);
  18755. if (meshIndex !== -1) {
  18756. shadowMap.renderList.splice(meshIndex, 1);
  18757. }
  18758. }
  18759. }
  18760. });
  18761. // Edges
  18762. if (this._edgesRenderer) {
  18763. this._edgesRenderer.dispose();
  18764. this._edgesRenderer = null;
  18765. }
  18766. // SubMeshes
  18767. if (this.getClassName() !== "InstancedMesh") {
  18768. this.releaseSubMeshes();
  18769. }
  18770. // Octree
  18771. var sceneOctree = this.getScene().selectionOctree;
  18772. if (sceneOctree !== undefined && sceneOctree !== null) {
  18773. var index = sceneOctree.dynamicContent.indexOf(this);
  18774. if (index !== -1) {
  18775. sceneOctree.dynamicContent.splice(index, 1);
  18776. }
  18777. }
  18778. // Query
  18779. var engine = this.getScene().getEngine();
  18780. if (this._occlusionQuery) {
  18781. this._isOcclusionQueryInProgress = false;
  18782. engine.deleteQuery(this._occlusionQuery);
  18783. this._occlusionQuery = null;
  18784. }
  18785. // Engine
  18786. engine.wipeCaches();
  18787. // Remove from scene
  18788. this.getScene().removeMesh(this);
  18789. if (disposeMaterialAndTextures) {
  18790. if (this.material) {
  18791. this.material.dispose(false, true);
  18792. }
  18793. }
  18794. if (!doNotRecurse) {
  18795. // Particles
  18796. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18797. if (this.getScene().particleSystems[index].emitter === this) {
  18798. this.getScene().particleSystems[index].dispose();
  18799. index--;
  18800. }
  18801. }
  18802. }
  18803. // facet data
  18804. if (this._facetDataEnabled) {
  18805. this.disableFacetData();
  18806. }
  18807. this.onAfterWorldMatrixUpdateObservable.clear();
  18808. this.onCollideObservable.clear();
  18809. this.onCollisionPositionChangeObservable.clear();
  18810. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18811. };
  18812. /**
  18813. * Adds the passed mesh as a child to the current mesh.
  18814. * Returns the AbstractMesh.
  18815. */
  18816. AbstractMesh.prototype.addChild = function (mesh) {
  18817. mesh.setParent(this);
  18818. return this;
  18819. };
  18820. /**
  18821. * Removes the passed mesh from the current mesh children list.
  18822. * Returns the AbstractMesh.
  18823. */
  18824. AbstractMesh.prototype.removeChild = function (mesh) {
  18825. mesh.setParent(null);
  18826. return this;
  18827. };
  18828. // Facet data
  18829. /**
  18830. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18831. * Returns the AbstractMesh.
  18832. */
  18833. AbstractMesh.prototype._initFacetData = function () {
  18834. if (!this._facetNormals) {
  18835. this._facetNormals = new Array();
  18836. }
  18837. if (!this._facetPositions) {
  18838. this._facetPositions = new Array();
  18839. }
  18840. if (!this._facetPartitioning) {
  18841. this._facetPartitioning = new Array();
  18842. }
  18843. this._facetNb = (this.getIndices().length / 3) | 0;
  18844. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18845. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18846. for (var f = 0; f < this._facetNb; f++) {
  18847. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18848. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18849. }
  18850. this._facetDataEnabled = true;
  18851. return this;
  18852. };
  18853. /**
  18854. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18855. * This method can be called within the render loop.
  18856. * 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.
  18857. * Returns the AbstractMesh.
  18858. */
  18859. AbstractMesh.prototype.updateFacetData = function () {
  18860. if (!this._facetDataEnabled) {
  18861. this._initFacetData();
  18862. }
  18863. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18864. var indices = this.getIndices();
  18865. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18866. var bInfo = this.getBoundingInfo();
  18867. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18868. // init arrays, matrix and sort function on first call
  18869. this._facetDepthSortEnabled = true;
  18870. if (indices instanceof Uint16Array) {
  18871. this._depthSortedIndices = new Uint16Array(indices);
  18872. }
  18873. else if (indices instanceof Uint32Array) {
  18874. this._depthSortedIndices = new Uint32Array(indices);
  18875. }
  18876. else {
  18877. var needs32bits = false;
  18878. for (var i = 0; i < indices.length; i++) {
  18879. if (indices[i] > 65535) {
  18880. needs32bits = true;
  18881. break;
  18882. }
  18883. }
  18884. if (needs32bits) {
  18885. this._depthSortedIndices = new Uint32Array(indices);
  18886. }
  18887. else {
  18888. this._depthSortedIndices = new Uint16Array(indices);
  18889. }
  18890. }
  18891. this._facetDepthSortFunction = function (f1, f2) {
  18892. return (f2.sqDistance - f1.sqDistance);
  18893. };
  18894. if (!this._facetDepthSortFrom) {
  18895. var camera = this.getScene().activeCamera;
  18896. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18897. }
  18898. this._depthSortedFacets = [];
  18899. for (var f = 0; f < this._facetNb; f++) {
  18900. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18901. this._depthSortedFacets.push(depthSortedFacet);
  18902. }
  18903. this._invertedMatrix = BABYLON.Matrix.Identity();
  18904. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18905. }
  18906. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18907. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18908. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18909. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18910. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18911. this._subDiv.max = this._partitioningSubdivisions;
  18912. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18913. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18914. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18915. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18916. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18917. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18918. // set the parameters for ComputeNormals()
  18919. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18920. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18921. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18922. this._facetParameters.bInfo = bInfo;
  18923. this._facetParameters.bbSize = this._bbSize;
  18924. this._facetParameters.subDiv = this._subDiv;
  18925. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18926. this._facetParameters.depthSort = this._facetDepthSort;
  18927. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18928. this.computeWorldMatrix(true);
  18929. this._worldMatrix.invertToRef(this._invertedMatrix);
  18930. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18931. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18932. }
  18933. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18934. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18935. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18936. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18937. var l = (this._depthSortedIndices.length / 3) | 0;
  18938. for (var f = 0; f < l; f++) {
  18939. var sind = this._depthSortedFacets[f].ind;
  18940. this._depthSortedIndices[f * 3] = indices[sind];
  18941. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18942. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18943. }
  18944. this.updateIndices(this._depthSortedIndices);
  18945. }
  18946. return this;
  18947. };
  18948. /**
  18949. * Returns the facetLocalNormals array.
  18950. * The normals are expressed in the mesh local space.
  18951. */
  18952. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18953. if (!this._facetNormals) {
  18954. this.updateFacetData();
  18955. }
  18956. return this._facetNormals;
  18957. };
  18958. /**
  18959. * Returns the facetLocalPositions array.
  18960. * The facet positions are expressed in the mesh local space.
  18961. */
  18962. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18963. if (!this._facetPositions) {
  18964. this.updateFacetData();
  18965. }
  18966. return this._facetPositions;
  18967. };
  18968. /**
  18969. * Returns the facetLocalPartioning array.
  18970. */
  18971. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18972. if (!this._facetPartitioning) {
  18973. this.updateFacetData();
  18974. }
  18975. return this._facetPartitioning;
  18976. };
  18977. /**
  18978. * Returns the i-th facet position in the world system.
  18979. * This method allocates a new Vector3 per call.
  18980. */
  18981. AbstractMesh.prototype.getFacetPosition = function (i) {
  18982. var pos = BABYLON.Vector3.Zero();
  18983. this.getFacetPositionToRef(i, pos);
  18984. return pos;
  18985. };
  18986. /**
  18987. * Sets the reference Vector3 with the i-th facet position in the world system.
  18988. * Returns the AbstractMesh.
  18989. */
  18990. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18991. var localPos = (this.getFacetLocalPositions())[i];
  18992. var world = this.getWorldMatrix();
  18993. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18994. return this;
  18995. };
  18996. /**
  18997. * Returns the i-th facet normal in the world system.
  18998. * This method allocates a new Vector3 per call.
  18999. */
  19000. AbstractMesh.prototype.getFacetNormal = function (i) {
  19001. var norm = BABYLON.Vector3.Zero();
  19002. this.getFacetNormalToRef(i, norm);
  19003. return norm;
  19004. };
  19005. /**
  19006. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19007. * Returns the AbstractMesh.
  19008. */
  19009. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19010. var localNorm = (this.getFacetLocalNormals())[i];
  19011. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19012. return this;
  19013. };
  19014. /**
  19015. * 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).
  19016. */
  19017. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19018. var bInfo = this.getBoundingInfo();
  19019. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19020. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19021. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19022. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19023. return null;
  19024. }
  19025. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19026. };
  19027. /**
  19028. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19029. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19030. * 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.
  19031. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19032. * 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.
  19033. */
  19034. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19035. if (checkFace === void 0) { checkFace = false; }
  19036. if (facing === void 0) { facing = true; }
  19037. var world = this.getWorldMatrix();
  19038. var invMat = BABYLON.Tmp.Matrix[5];
  19039. world.invertToRef(invMat);
  19040. var invVect = BABYLON.Tmp.Vector3[8];
  19041. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19042. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19043. if (projected) {
  19044. // tranform the local computed projected vector to world coordinates
  19045. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19046. }
  19047. return closest;
  19048. };
  19049. /**
  19050. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19051. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19052. * 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.
  19053. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19054. * 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.
  19055. */
  19056. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19057. if (checkFace === void 0) { checkFace = false; }
  19058. if (facing === void 0) { facing = true; }
  19059. var closest = null;
  19060. var tmpx = 0.0;
  19061. var tmpy = 0.0;
  19062. var tmpz = 0.0;
  19063. var d = 0.0; // tmp dot facet normal * facet position
  19064. var t0 = 0.0;
  19065. var projx = 0.0;
  19066. var projy = 0.0;
  19067. var projz = 0.0;
  19068. // Get all the facets in the same partitioning block than (x, y, z)
  19069. var facetPositions = this.getFacetLocalPositions();
  19070. var facetNormals = this.getFacetLocalNormals();
  19071. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19072. if (!facetsInBlock) {
  19073. return null;
  19074. }
  19075. // Get the closest facet to (x, y, z)
  19076. var shortest = Number.MAX_VALUE; // init distance vars
  19077. var tmpDistance = shortest;
  19078. var fib; // current facet in the block
  19079. var norm; // current facet normal
  19080. var p0; // current facet barycenter position
  19081. // loop on all the facets in the current partitioning block
  19082. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19083. fib = facetsInBlock[idx];
  19084. norm = facetNormals[fib];
  19085. p0 = facetPositions[fib];
  19086. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19087. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19088. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19089. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19090. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19091. projx = x + norm.x * t0;
  19092. projy = y + norm.y * t0;
  19093. projz = z + norm.z * t0;
  19094. tmpx = projx - x;
  19095. tmpy = projy - y;
  19096. tmpz = projz - z;
  19097. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19098. if (tmpDistance < shortest) {
  19099. shortest = tmpDistance;
  19100. closest = fib;
  19101. if (projected) {
  19102. projected.x = projx;
  19103. projected.y = projy;
  19104. projected.z = projz;
  19105. }
  19106. }
  19107. }
  19108. }
  19109. return closest;
  19110. };
  19111. /**
  19112. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19113. */
  19114. AbstractMesh.prototype.getFacetDataParameters = function () {
  19115. return this._facetParameters;
  19116. };
  19117. /**
  19118. * Disables the feature FacetData and frees the related memory.
  19119. * Returns the AbstractMesh.
  19120. */
  19121. AbstractMesh.prototype.disableFacetData = function () {
  19122. if (this._facetDataEnabled) {
  19123. this._facetDataEnabled = false;
  19124. this._facetPositions = new Array();
  19125. this._facetNormals = new Array();
  19126. this._facetPartitioning = new Array();
  19127. this._facetParameters = null;
  19128. this._depthSortedIndices = new Uint32Array(0);
  19129. }
  19130. return this;
  19131. };
  19132. /**
  19133. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19134. * Returns the mesh.
  19135. */
  19136. AbstractMesh.prototype.updateIndices = function (indices) {
  19137. return this;
  19138. };
  19139. /**
  19140. * The mesh Geometry. Actually used by the Mesh object.
  19141. * Returns a blank geometry object.
  19142. */
  19143. /**
  19144. * Creates new normals data for the mesh.
  19145. * @param updatable.
  19146. */
  19147. AbstractMesh.prototype.createNormals = function (updatable) {
  19148. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19149. var indices = this.getIndices();
  19150. var normals;
  19151. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19152. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19153. }
  19154. else {
  19155. normals = [];
  19156. }
  19157. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19158. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19159. };
  19160. /**
  19161. * Align the mesh with a normal.
  19162. * Returns the mesh.
  19163. */
  19164. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19165. if (!upDirection) {
  19166. upDirection = BABYLON.Axis.Y;
  19167. }
  19168. var axisX = BABYLON.Tmp.Vector3[0];
  19169. var axisZ = BABYLON.Tmp.Vector3[1];
  19170. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19171. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19172. if (this.rotationQuaternion) {
  19173. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19174. }
  19175. else {
  19176. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19177. }
  19178. return this;
  19179. };
  19180. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19181. var engine = this.getEngine();
  19182. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19183. this._isOccluded = false;
  19184. return;
  19185. }
  19186. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19187. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19188. if (isOcclusionQueryAvailable) {
  19189. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19190. this._isOcclusionQueryInProgress = false;
  19191. this._occlusionInternalRetryCounter = 0;
  19192. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19193. }
  19194. else {
  19195. this._occlusionInternalRetryCounter++;
  19196. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19197. this._isOcclusionQueryInProgress = false;
  19198. this._occlusionInternalRetryCounter = 0;
  19199. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19200. // if strict continue the last state of the object.
  19201. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19202. }
  19203. else {
  19204. return;
  19205. }
  19206. }
  19207. }
  19208. var scene = this.getScene();
  19209. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19210. if (!this._occlusionQuery) {
  19211. this._occlusionQuery = engine.createQuery();
  19212. }
  19213. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19214. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19215. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19216. this._isOcclusionQueryInProgress = true;
  19217. };
  19218. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19219. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19220. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19221. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19222. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19223. return AbstractMesh;
  19224. }(BABYLON.TransformNode));
  19225. BABYLON.AbstractMesh = AbstractMesh;
  19226. })(BABYLON || (BABYLON = {}));
  19227. //# sourceMappingURL=babylon.abstractMesh.js.map
  19228. "use strict";
  19229. var BABYLON;
  19230. (function (BABYLON) {
  19231. /**
  19232. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19233. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19234. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  19235. */
  19236. var Light = /** @class */ (function (_super) {
  19237. __extends(Light, _super);
  19238. /**
  19239. * Creates a Light object in the scene.
  19240. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19241. * @param name The firendly name of the light
  19242. * @param scene The scene the light belongs too
  19243. */
  19244. function Light(name, scene) {
  19245. var _this = _super.call(this, name, scene) || this;
  19246. /**
  19247. * Diffuse gives the basic color to an object.
  19248. */
  19249. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19250. /**
  19251. * Specular produces a highlight color on an object.
  19252. * Note: This is note affecting PBR materials.
  19253. */
  19254. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19255. /**
  19256. * Strength of the light.
  19257. * Note: By default it is define in the framework own unit.
  19258. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19259. */
  19260. _this.intensity = 1.0;
  19261. /**
  19262. * Defines how far from the source the light is impacting in scene units.
  19263. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19264. */
  19265. _this.range = Number.MAX_VALUE;
  19266. /**
  19267. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19268. * of light.
  19269. */
  19270. _this._photometricScale = 1.0;
  19271. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19272. _this._radius = 0.00001;
  19273. /**
  19274. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19275. * exceeding the number allowed of the materials.
  19276. */
  19277. _this.renderPriority = 0;
  19278. /**
  19279. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19280. * the current shadow generator.
  19281. */
  19282. _this.shadowEnabled = true;
  19283. _this._excludeWithLayerMask = 0;
  19284. _this._includeOnlyWithLayerMask = 0;
  19285. _this._lightmapMode = 0;
  19286. /**
  19287. * @ignore Internal use only.
  19288. */
  19289. _this._excludedMeshesIds = new Array();
  19290. /**
  19291. * @ignore Internal use only.
  19292. */
  19293. _this._includedOnlyMeshesIds = new Array();
  19294. _this.getScene().addLight(_this);
  19295. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19296. _this._buildUniformLayout();
  19297. _this.includedOnlyMeshes = new Array();
  19298. _this.excludedMeshes = new Array();
  19299. _this._resyncMeshes();
  19300. return _this;
  19301. }
  19302. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19303. /**
  19304. * If every light affecting the material is in this lightmapMode,
  19305. * material.lightmapTexture adds or multiplies
  19306. * (depends on material.useLightmapAsShadowmap)
  19307. * after every other light calculations.
  19308. */
  19309. get: function () {
  19310. return Light._LIGHTMAP_DEFAULT;
  19311. },
  19312. enumerable: true,
  19313. configurable: true
  19314. });
  19315. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19316. /**
  19317. * material.lightmapTexture as only diffuse lighting from this light
  19318. * adds only specular lighting from this light
  19319. * adds dynamic shadows
  19320. */
  19321. get: function () {
  19322. return Light._LIGHTMAP_SPECULAR;
  19323. },
  19324. enumerable: true,
  19325. configurable: true
  19326. });
  19327. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19328. /**
  19329. * material.lightmapTexture as only lighting
  19330. * no light calculation from this light
  19331. * only adds dynamic shadows from this light
  19332. */
  19333. get: function () {
  19334. return Light._LIGHTMAP_SHADOWSONLY;
  19335. },
  19336. enumerable: true,
  19337. configurable: true
  19338. });
  19339. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19340. /**
  19341. * Each light type uses the default quantity according to its type:
  19342. * point/spot lights use luminous intensity
  19343. * directional lights use illuminance
  19344. */
  19345. get: function () {
  19346. return Light._INTENSITYMODE_AUTOMATIC;
  19347. },
  19348. enumerable: true,
  19349. configurable: true
  19350. });
  19351. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19352. /**
  19353. * lumen (lm)
  19354. */
  19355. get: function () {
  19356. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19357. },
  19358. enumerable: true,
  19359. configurable: true
  19360. });
  19361. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19362. /**
  19363. * candela (lm/sr)
  19364. */
  19365. get: function () {
  19366. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19367. },
  19368. enumerable: true,
  19369. configurable: true
  19370. });
  19371. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19372. /**
  19373. * lux (lm/m^2)
  19374. */
  19375. get: function () {
  19376. return Light._INTENSITYMODE_ILLUMINANCE;
  19377. },
  19378. enumerable: true,
  19379. configurable: true
  19380. });
  19381. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19382. /**
  19383. * nit (cd/m^2)
  19384. */
  19385. get: function () {
  19386. return Light._INTENSITYMODE_LUMINANCE;
  19387. },
  19388. enumerable: true,
  19389. configurable: true
  19390. });
  19391. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19392. /**
  19393. * Light type const id of the point light.
  19394. */
  19395. get: function () {
  19396. return Light._LIGHTTYPEID_POINTLIGHT;
  19397. },
  19398. enumerable: true,
  19399. configurable: true
  19400. });
  19401. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19402. /**
  19403. * Light type const id of the directional light.
  19404. */
  19405. get: function () {
  19406. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19407. },
  19408. enumerable: true,
  19409. configurable: true
  19410. });
  19411. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19412. /**
  19413. * Light type const id of the spot light.
  19414. */
  19415. get: function () {
  19416. return Light._LIGHTTYPEID_SPOTLIGHT;
  19417. },
  19418. enumerable: true,
  19419. configurable: true
  19420. });
  19421. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19422. /**
  19423. * Light type const id of the hemispheric light.
  19424. */
  19425. get: function () {
  19426. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19427. },
  19428. enumerable: true,
  19429. configurable: true
  19430. });
  19431. Object.defineProperty(Light.prototype, "intensityMode", {
  19432. /**
  19433. * Gets the photometric scale used to interpret the intensity.
  19434. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19435. */
  19436. get: function () {
  19437. return this._intensityMode;
  19438. },
  19439. /**
  19440. * Sets the photometric scale used to interpret the intensity.
  19441. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19442. */
  19443. set: function (value) {
  19444. this._intensityMode = value;
  19445. this._computePhotometricScale();
  19446. },
  19447. enumerable: true,
  19448. configurable: true
  19449. });
  19450. ;
  19451. ;
  19452. Object.defineProperty(Light.prototype, "radius", {
  19453. /**
  19454. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19455. */
  19456. get: function () {
  19457. return this._radius;
  19458. },
  19459. /**
  19460. * sets the light radius used by PBR Materials to simulate soft area lights.
  19461. */
  19462. set: function (value) {
  19463. this._radius = value;
  19464. this._computePhotometricScale();
  19465. },
  19466. enumerable: true,
  19467. configurable: true
  19468. });
  19469. ;
  19470. ;
  19471. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19472. /**
  19473. * Gets the only meshes impacted by this light.
  19474. */
  19475. get: function () {
  19476. return this._includedOnlyMeshes;
  19477. },
  19478. /**
  19479. * Sets the only meshes impacted by this light.
  19480. */
  19481. set: function (value) {
  19482. this._includedOnlyMeshes = value;
  19483. this._hookArrayForIncludedOnly(value);
  19484. },
  19485. enumerable: true,
  19486. configurable: true
  19487. });
  19488. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19489. /**
  19490. * Gets the meshes not impacted by this light.
  19491. */
  19492. get: function () {
  19493. return this._excludedMeshes;
  19494. },
  19495. /**
  19496. * Sets the meshes not impacted by this light.
  19497. */
  19498. set: function (value) {
  19499. this._excludedMeshes = value;
  19500. this._hookArrayForExcluded(value);
  19501. },
  19502. enumerable: true,
  19503. configurable: true
  19504. });
  19505. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19506. /**
  19507. * Gets the layer id use to find what meshes are not impacted by the light.
  19508. * Inactive if 0
  19509. */
  19510. get: function () {
  19511. return this._excludeWithLayerMask;
  19512. },
  19513. /**
  19514. * Sets the layer id use to find what meshes are not impacted by the light.
  19515. * Inactive if 0
  19516. */
  19517. set: function (value) {
  19518. this._excludeWithLayerMask = value;
  19519. this._resyncMeshes();
  19520. },
  19521. enumerable: true,
  19522. configurable: true
  19523. });
  19524. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19525. /**
  19526. * Gets the layer id use to find what meshes are impacted by the light.
  19527. * Inactive if 0
  19528. */
  19529. get: function () {
  19530. return this._includeOnlyWithLayerMask;
  19531. },
  19532. /**
  19533. * Sets the layer id use to find what meshes are impacted by the light.
  19534. * Inactive if 0
  19535. */
  19536. set: function (value) {
  19537. this._includeOnlyWithLayerMask = value;
  19538. this._resyncMeshes();
  19539. },
  19540. enumerable: true,
  19541. configurable: true
  19542. });
  19543. Object.defineProperty(Light.prototype, "lightmapMode", {
  19544. /**
  19545. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19546. */
  19547. get: function () {
  19548. return this._lightmapMode;
  19549. },
  19550. /**
  19551. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19552. */
  19553. set: function (value) {
  19554. if (this._lightmapMode === value) {
  19555. return;
  19556. }
  19557. this._lightmapMode = value;
  19558. this._markMeshesAsLightDirty();
  19559. },
  19560. enumerable: true,
  19561. configurable: true
  19562. });
  19563. /**
  19564. * Returns the string "Light".
  19565. * @returns the class name
  19566. */
  19567. Light.prototype.getClassName = function () {
  19568. return "Light";
  19569. };
  19570. /**
  19571. * Converts the light information to a readable string for debug purpose.
  19572. * @param fullDetails Supports for multiple levels of logging within scene loading
  19573. * @returns the human readable light info
  19574. */
  19575. Light.prototype.toString = function (fullDetails) {
  19576. var ret = "Name: " + this.name;
  19577. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19578. if (this.animations) {
  19579. for (var i = 0; i < this.animations.length; i++) {
  19580. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19581. }
  19582. }
  19583. if (fullDetails) {
  19584. }
  19585. return ret;
  19586. };
  19587. /**
  19588. * Set the enabled state of this node.
  19589. * @param value - the new enabled state
  19590. * @see isEnabled
  19591. */
  19592. Light.prototype.setEnabled = function (value) {
  19593. _super.prototype.setEnabled.call(this, value);
  19594. this._resyncMeshes();
  19595. };
  19596. /**
  19597. * Returns the Light associated shadow generator if any.
  19598. * @return the associated shadow generator.
  19599. */
  19600. Light.prototype.getShadowGenerator = function () {
  19601. return this._shadowGenerator;
  19602. };
  19603. /**
  19604. * Returns a Vector3, the absolute light position in the World.
  19605. * @returns the world space position of the light
  19606. */
  19607. Light.prototype.getAbsolutePosition = function () {
  19608. return BABYLON.Vector3.Zero();
  19609. };
  19610. /**
  19611. * Specifies if the light will affect the passed mesh.
  19612. * @param mesh The mesh to test against the light
  19613. * @return true the mesh is affected otherwise, false.
  19614. */
  19615. Light.prototype.canAffectMesh = function (mesh) {
  19616. if (!mesh) {
  19617. return true;
  19618. }
  19619. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19620. return false;
  19621. }
  19622. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19623. return false;
  19624. }
  19625. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19626. return false;
  19627. }
  19628. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19629. return false;
  19630. }
  19631. return true;
  19632. };
  19633. /**
  19634. * Computes and Returns the light World matrix.
  19635. * @returns the world matrix
  19636. */
  19637. Light.prototype.getWorldMatrix = function () {
  19638. this._currentRenderId = this.getScene().getRenderId();
  19639. var worldMatrix = this._getWorldMatrix();
  19640. if (this.parent && this.parent.getWorldMatrix) {
  19641. if (!this._parentedWorldMatrix) {
  19642. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19643. }
  19644. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19645. this._markSyncedWithParent();
  19646. return this._parentedWorldMatrix;
  19647. }
  19648. return worldMatrix;
  19649. };
  19650. /**
  19651. * Sort function to order lights for rendering.
  19652. * @param a First Light object to compare to second.
  19653. * @param b Second Light object to compare first.
  19654. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19655. */
  19656. Light.CompareLightsPriority = function (a, b) {
  19657. //shadow-casting lights have priority over non-shadow-casting lights
  19658. //the renderPrioirty is a secondary sort criterion
  19659. if (a.shadowEnabled !== b.shadowEnabled) {
  19660. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19661. }
  19662. return b.renderPriority - a.renderPriority;
  19663. };
  19664. /**
  19665. * Releases resources associated with this node.
  19666. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19667. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19668. */
  19669. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19670. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19671. if (this._shadowGenerator) {
  19672. this._shadowGenerator.dispose();
  19673. this._shadowGenerator = null;
  19674. }
  19675. // Animations
  19676. this.getScene().stopAnimation(this);
  19677. // Remove from meshes
  19678. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19679. var mesh = _a[_i];
  19680. mesh._removeLightSource(this);
  19681. }
  19682. this._uniformBuffer.dispose();
  19683. // Remove from scene
  19684. this.getScene().removeLight(this);
  19685. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19686. };
  19687. /**
  19688. * Returns the light type ID (integer).
  19689. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19690. */
  19691. Light.prototype.getTypeID = function () {
  19692. return 0;
  19693. };
  19694. /**
  19695. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19696. * @returns the scaled intensity in intensity mode unit
  19697. */
  19698. Light.prototype.getScaledIntensity = function () {
  19699. return this._photometricScale * this.intensity;
  19700. };
  19701. /**
  19702. * Returns a new Light object, named "name", from the current one.
  19703. * @param name The name of the cloned light
  19704. * @returns the new created light
  19705. */
  19706. Light.prototype.clone = function (name) {
  19707. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19708. if (!constructor) {
  19709. return null;
  19710. }
  19711. return BABYLON.SerializationHelper.Clone(constructor, this);
  19712. };
  19713. /**
  19714. * Serializes the current light into a Serialization object.
  19715. * @returns the serialized object.
  19716. */
  19717. Light.prototype.serialize = function () {
  19718. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19719. // Type
  19720. serializationObject.type = this.getTypeID();
  19721. // Parent
  19722. if (this.parent) {
  19723. serializationObject.parentId = this.parent.id;
  19724. }
  19725. // Inclusion / exclusions
  19726. if (this.excludedMeshes.length > 0) {
  19727. serializationObject.excludedMeshesIds = [];
  19728. this.excludedMeshes.forEach(function (mesh) {
  19729. serializationObject.excludedMeshesIds.push(mesh.id);
  19730. });
  19731. }
  19732. if (this.includedOnlyMeshes.length > 0) {
  19733. serializationObject.includedOnlyMeshesIds = [];
  19734. this.includedOnlyMeshes.forEach(function (mesh) {
  19735. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19736. });
  19737. }
  19738. // Animations
  19739. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19740. serializationObject.ranges = this.serializeAnimationRanges();
  19741. return serializationObject;
  19742. };
  19743. /**
  19744. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19745. * This new light is named "name" and added to the passed scene.
  19746. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19747. * @param name The friendly name of the light
  19748. * @param scene The scene the new light will belong to
  19749. * @returns the constructor function
  19750. */
  19751. Light.GetConstructorFromName = function (type, name, scene) {
  19752. switch (type) {
  19753. case 0:
  19754. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19755. case 1:
  19756. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19757. case 2:
  19758. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19759. case 3:
  19760. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19761. }
  19762. return null;
  19763. };
  19764. /**
  19765. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19766. * @param parsedLight The JSON representation of the light
  19767. * @param scene The scene to create the parsed light in
  19768. * @returns the created light after parsing
  19769. */
  19770. Light.Parse = function (parsedLight, scene) {
  19771. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19772. if (!constructor) {
  19773. return null;
  19774. }
  19775. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19776. // Inclusion / exclusions
  19777. if (parsedLight.excludedMeshesIds) {
  19778. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19779. }
  19780. if (parsedLight.includedOnlyMeshesIds) {
  19781. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19782. }
  19783. // Parent
  19784. if (parsedLight.parentId) {
  19785. light._waitingParentId = parsedLight.parentId;
  19786. }
  19787. // Animations
  19788. if (parsedLight.animations) {
  19789. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19790. var parsedAnimation = parsedLight.animations[animationIndex];
  19791. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19792. }
  19793. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19794. }
  19795. if (parsedLight.autoAnimate) {
  19796. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19797. }
  19798. return light;
  19799. };
  19800. Light.prototype._hookArrayForExcluded = function (array) {
  19801. var _this = this;
  19802. var oldPush = array.push;
  19803. array.push = function () {
  19804. var items = [];
  19805. for (var _i = 0; _i < arguments.length; _i++) {
  19806. items[_i] = arguments[_i];
  19807. }
  19808. var result = oldPush.apply(array, items);
  19809. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19810. var item = items_1[_a];
  19811. item._resyncLighSource(_this);
  19812. }
  19813. return result;
  19814. };
  19815. var oldSplice = array.splice;
  19816. array.splice = function (index, deleteCount) {
  19817. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19818. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19819. var item = deleted_1[_i];
  19820. item._resyncLighSource(_this);
  19821. }
  19822. return deleted;
  19823. };
  19824. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19825. var item = array_1[_i];
  19826. item._resyncLighSource(this);
  19827. }
  19828. };
  19829. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19830. var _this = this;
  19831. var oldPush = array.push;
  19832. array.push = function () {
  19833. var items = [];
  19834. for (var _i = 0; _i < arguments.length; _i++) {
  19835. items[_i] = arguments[_i];
  19836. }
  19837. var result = oldPush.apply(array, items);
  19838. _this._resyncMeshes();
  19839. return result;
  19840. };
  19841. var oldSplice = array.splice;
  19842. array.splice = function (index, deleteCount) {
  19843. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19844. _this._resyncMeshes();
  19845. return deleted;
  19846. };
  19847. this._resyncMeshes();
  19848. };
  19849. Light.prototype._resyncMeshes = function () {
  19850. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19851. var mesh = _a[_i];
  19852. mesh._resyncLighSource(this);
  19853. }
  19854. };
  19855. /**
  19856. * Forces the meshes to update their light related information in their rendering used effects
  19857. * @ignore Internal Use Only
  19858. */
  19859. Light.prototype._markMeshesAsLightDirty = function () {
  19860. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19861. var mesh = _a[_i];
  19862. if (mesh._lightSources.indexOf(this) !== -1) {
  19863. mesh._markSubMeshesAsLightDirty();
  19864. }
  19865. }
  19866. };
  19867. /**
  19868. * Recomputes the cached photometric scale if needed.
  19869. */
  19870. Light.prototype._computePhotometricScale = function () {
  19871. this._photometricScale = this._getPhotometricScale();
  19872. this.getScene().resetCachedMaterial();
  19873. };
  19874. /**
  19875. * Returns the Photometric Scale according to the light type and intensity mode.
  19876. */
  19877. Light.prototype._getPhotometricScale = function () {
  19878. var photometricScale = 0.0;
  19879. var lightTypeID = this.getTypeID();
  19880. //get photometric mode
  19881. var photometricMode = this.intensityMode;
  19882. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19883. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19884. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19885. }
  19886. else {
  19887. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19888. }
  19889. }
  19890. //compute photometric scale
  19891. switch (lightTypeID) {
  19892. case Light.LIGHTTYPEID_POINTLIGHT:
  19893. case Light.LIGHTTYPEID_SPOTLIGHT:
  19894. switch (photometricMode) {
  19895. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19896. photometricScale = 1.0 / (4.0 * Math.PI);
  19897. break;
  19898. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19899. photometricScale = 1.0;
  19900. break;
  19901. case Light.INTENSITYMODE_LUMINANCE:
  19902. photometricScale = this.radius * this.radius;
  19903. break;
  19904. }
  19905. break;
  19906. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19907. switch (photometricMode) {
  19908. case Light.INTENSITYMODE_ILLUMINANCE:
  19909. photometricScale = 1.0;
  19910. break;
  19911. case Light.INTENSITYMODE_LUMINANCE:
  19912. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19913. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19914. var apexAngleRadians = this.radius;
  19915. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19916. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19917. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19918. photometricScale = solidAngle;
  19919. break;
  19920. }
  19921. break;
  19922. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19923. // No fall off in hemisperic light.
  19924. photometricScale = 1.0;
  19925. break;
  19926. }
  19927. return photometricScale;
  19928. };
  19929. /**
  19930. * Reorder the light in the scene according to their defined priority.
  19931. * @ignore Internal Use Only
  19932. */
  19933. Light.prototype._reorderLightsInScene = function () {
  19934. var scene = this.getScene();
  19935. if (this._renderPriority != 0) {
  19936. scene.requireLightSorting = true;
  19937. }
  19938. this.getScene().sortLightsByPriority();
  19939. };
  19940. //lightmapMode Consts
  19941. Light._LIGHTMAP_DEFAULT = 0;
  19942. Light._LIGHTMAP_SPECULAR = 1;
  19943. Light._LIGHTMAP_SHADOWSONLY = 2;
  19944. // Intensity Mode Consts
  19945. Light._INTENSITYMODE_AUTOMATIC = 0;
  19946. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19947. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19948. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19949. Light._INTENSITYMODE_LUMINANCE = 4;
  19950. // Light types ids const.
  19951. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19952. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19953. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19954. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19955. __decorate([
  19956. BABYLON.serializeAsColor3()
  19957. ], Light.prototype, "diffuse", void 0);
  19958. __decorate([
  19959. BABYLON.serializeAsColor3()
  19960. ], Light.prototype, "specular", void 0);
  19961. __decorate([
  19962. BABYLON.serialize()
  19963. ], Light.prototype, "intensity", void 0);
  19964. __decorate([
  19965. BABYLON.serialize()
  19966. ], Light.prototype, "range", void 0);
  19967. __decorate([
  19968. BABYLON.serialize()
  19969. ], Light.prototype, "intensityMode", null);
  19970. __decorate([
  19971. BABYLON.serialize()
  19972. ], Light.prototype, "radius", null);
  19973. __decorate([
  19974. BABYLON.serialize()
  19975. ], Light.prototype, "_renderPriority", void 0);
  19976. __decorate([
  19977. BABYLON.expandToProperty("_reorderLightsInScene")
  19978. ], Light.prototype, "renderPriority", void 0);
  19979. __decorate([
  19980. BABYLON.serialize()
  19981. ], Light.prototype, "shadowEnabled", void 0);
  19982. __decorate([
  19983. BABYLON.serialize("excludeWithLayerMask")
  19984. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19985. __decorate([
  19986. BABYLON.serialize("includeOnlyWithLayerMask")
  19987. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19988. __decorate([
  19989. BABYLON.serialize("lightmapMode")
  19990. ], Light.prototype, "_lightmapMode", void 0);
  19991. return Light;
  19992. }(BABYLON.Node));
  19993. BABYLON.Light = Light;
  19994. })(BABYLON || (BABYLON = {}));
  19995. //# sourceMappingURL=babylon.light.js.map
  19996. "use strict";
  19997. var BABYLON;
  19998. (function (BABYLON) {
  19999. var Camera = /** @class */ (function (_super) {
  20000. __extends(Camera, _super);
  20001. function Camera(name, position, scene) {
  20002. var _this = _super.call(this, name, scene) || this;
  20003. /**
  20004. * The vector the camera should consider as up.
  20005. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20006. */
  20007. _this.upVector = BABYLON.Vector3.Up();
  20008. _this.orthoLeft = null;
  20009. _this.orthoRight = null;
  20010. _this.orthoBottom = null;
  20011. _this.orthoTop = null;
  20012. /**
  20013. * FOV is set in Radians. (default is 0.8)
  20014. */
  20015. _this.fov = 0.8;
  20016. _this.minZ = 1;
  20017. _this.maxZ = 10000.0;
  20018. _this.inertia = 0.9;
  20019. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20020. _this.isIntermediate = false;
  20021. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20022. /**
  20023. * Restricts the camera to viewing objects with the same layerMask.
  20024. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20025. */
  20026. _this.layerMask = 0x0FFFFFFF;
  20027. /**
  20028. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20029. */
  20030. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20031. // Camera rig members
  20032. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20033. _this._rigCameras = new Array();
  20034. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20035. _this._skipRendering = false;
  20036. _this.customRenderTargets = new Array();
  20037. // Observables
  20038. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20039. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20040. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20041. _this.onRestoreStateObservable = new BABYLON.Observable();
  20042. // Cache
  20043. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20044. _this._projectionMatrix = new BABYLON.Matrix();
  20045. _this._doNotComputeProjectionMatrix = false;
  20046. _this._postProcesses = new Array();
  20047. _this._transformMatrix = BABYLON.Matrix.Zero();
  20048. _this._activeMeshes = new BABYLON.SmartArray(256);
  20049. _this._globalPosition = BABYLON.Vector3.Zero();
  20050. _this._refreshFrustumPlanes = true;
  20051. _this.getScene().addCamera(_this);
  20052. if (!_this.getScene().activeCamera) {
  20053. _this.getScene().activeCamera = _this;
  20054. }
  20055. _this.position = position;
  20056. return _this;
  20057. }
  20058. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20059. get: function () {
  20060. return Camera._PERSPECTIVE_CAMERA;
  20061. },
  20062. enumerable: true,
  20063. configurable: true
  20064. });
  20065. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20066. get: function () {
  20067. return Camera._ORTHOGRAPHIC_CAMERA;
  20068. },
  20069. enumerable: true,
  20070. configurable: true
  20071. });
  20072. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20073. /**
  20074. * This is the default FOV mode for perspective cameras.
  20075. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20076. *
  20077. */
  20078. get: function () {
  20079. return Camera._FOVMODE_VERTICAL_FIXED;
  20080. },
  20081. enumerable: true,
  20082. configurable: true
  20083. });
  20084. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20085. /**
  20086. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20087. *
  20088. */
  20089. get: function () {
  20090. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20091. },
  20092. enumerable: true,
  20093. configurable: true
  20094. });
  20095. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20096. get: function () {
  20097. return Camera._RIG_MODE_NONE;
  20098. },
  20099. enumerable: true,
  20100. configurable: true
  20101. });
  20102. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20103. get: function () {
  20104. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20105. },
  20106. enumerable: true,
  20107. configurable: true
  20108. });
  20109. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20110. get: function () {
  20111. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20112. },
  20113. enumerable: true,
  20114. configurable: true
  20115. });
  20116. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20117. get: function () {
  20118. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20119. },
  20120. enumerable: true,
  20121. configurable: true
  20122. });
  20123. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20124. get: function () {
  20125. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20126. },
  20127. enumerable: true,
  20128. configurable: true
  20129. });
  20130. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20131. get: function () {
  20132. return Camera._RIG_MODE_VR;
  20133. },
  20134. enumerable: true,
  20135. configurable: true
  20136. });
  20137. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20138. get: function () {
  20139. return Camera._RIG_MODE_WEBVR;
  20140. },
  20141. enumerable: true,
  20142. configurable: true
  20143. });
  20144. /**
  20145. * Store current camera state (fov, position, etc..)
  20146. */
  20147. Camera.prototype.storeState = function () {
  20148. this._stateStored = true;
  20149. this._storedFov = this.fov;
  20150. return this;
  20151. };
  20152. /**
  20153. * Restores the camera state values if it has been stored. You must call storeState() first
  20154. */
  20155. Camera.prototype._restoreStateValues = function () {
  20156. if (!this._stateStored) {
  20157. return false;
  20158. }
  20159. this.fov = this._storedFov;
  20160. return true;
  20161. };
  20162. /**
  20163. * Restored camera state. You must call storeState() first
  20164. */
  20165. Camera.prototype.restoreState = function () {
  20166. if (this._restoreStateValues()) {
  20167. this.onRestoreStateObservable.notifyObservers(this);
  20168. return true;
  20169. }
  20170. return false;
  20171. };
  20172. Camera.prototype.getClassName = function () {
  20173. return "Camera";
  20174. };
  20175. /**
  20176. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20177. */
  20178. Camera.prototype.toString = function (fullDetails) {
  20179. var ret = "Name: " + this.name;
  20180. ret += ", type: " + this.getClassName();
  20181. if (this.animations) {
  20182. for (var i = 0; i < this.animations.length; i++) {
  20183. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20184. }
  20185. }
  20186. if (fullDetails) {
  20187. }
  20188. return ret;
  20189. };
  20190. Object.defineProperty(Camera.prototype, "globalPosition", {
  20191. get: function () {
  20192. return this._globalPosition;
  20193. },
  20194. enumerable: true,
  20195. configurable: true
  20196. });
  20197. Camera.prototype.getActiveMeshes = function () {
  20198. return this._activeMeshes;
  20199. };
  20200. Camera.prototype.isActiveMesh = function (mesh) {
  20201. return (this._activeMeshes.indexOf(mesh) !== -1);
  20202. };
  20203. //Cache
  20204. Camera.prototype._initCache = function () {
  20205. _super.prototype._initCache.call(this);
  20206. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20207. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20208. this._cache.mode = undefined;
  20209. this._cache.minZ = undefined;
  20210. this._cache.maxZ = undefined;
  20211. this._cache.fov = undefined;
  20212. this._cache.fovMode = undefined;
  20213. this._cache.aspectRatio = undefined;
  20214. this._cache.orthoLeft = undefined;
  20215. this._cache.orthoRight = undefined;
  20216. this._cache.orthoBottom = undefined;
  20217. this._cache.orthoTop = undefined;
  20218. this._cache.renderWidth = undefined;
  20219. this._cache.renderHeight = undefined;
  20220. };
  20221. Camera.prototype._updateCache = function (ignoreParentClass) {
  20222. if (!ignoreParentClass) {
  20223. _super.prototype._updateCache.call(this);
  20224. }
  20225. this._cache.position.copyFrom(this.position);
  20226. this._cache.upVector.copyFrom(this.upVector);
  20227. };
  20228. // Synchronized
  20229. Camera.prototype._isSynchronized = function () {
  20230. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20231. };
  20232. Camera.prototype._isSynchronizedViewMatrix = function () {
  20233. if (!_super.prototype._isSynchronized.call(this))
  20234. return false;
  20235. return this._cache.position.equals(this.position)
  20236. && this._cache.upVector.equals(this.upVector)
  20237. && this.isSynchronizedWithParent();
  20238. };
  20239. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20240. var check = this._cache.mode === this.mode
  20241. && this._cache.minZ === this.minZ
  20242. && this._cache.maxZ === this.maxZ;
  20243. if (!check) {
  20244. return false;
  20245. }
  20246. var engine = this.getEngine();
  20247. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20248. check = this._cache.fov === this.fov
  20249. && this._cache.fovMode === this.fovMode
  20250. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20251. }
  20252. else {
  20253. check = this._cache.orthoLeft === this.orthoLeft
  20254. && this._cache.orthoRight === this.orthoRight
  20255. && this._cache.orthoBottom === this.orthoBottom
  20256. && this._cache.orthoTop === this.orthoTop
  20257. && this._cache.renderWidth === engine.getRenderWidth()
  20258. && this._cache.renderHeight === engine.getRenderHeight();
  20259. }
  20260. return check;
  20261. };
  20262. // Controls
  20263. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20264. };
  20265. Camera.prototype.detachControl = function (element) {
  20266. };
  20267. Camera.prototype.update = function () {
  20268. this._checkInputs();
  20269. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20270. this._updateRigCameras();
  20271. }
  20272. };
  20273. Camera.prototype._checkInputs = function () {
  20274. this.onAfterCheckInputsObservable.notifyObservers(this);
  20275. };
  20276. Object.defineProperty(Camera.prototype, "rigCameras", {
  20277. get: function () {
  20278. return this._rigCameras;
  20279. },
  20280. enumerable: true,
  20281. configurable: true
  20282. });
  20283. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20284. get: function () {
  20285. return this._rigPostProcess;
  20286. },
  20287. enumerable: true,
  20288. configurable: true
  20289. });
  20290. /**
  20291. * Internal, gets the first post proces.
  20292. * @returns the first post process to be run on this camera.
  20293. */
  20294. Camera.prototype._getFirstPostProcess = function () {
  20295. for (var pp in this._postProcesses) {
  20296. if (this._postProcesses[pp] !== null) {
  20297. return this._postProcesses[pp];
  20298. }
  20299. }
  20300. return null;
  20301. };
  20302. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20303. // invalidate framebuffer
  20304. var firstPostProcess = this._getFirstPostProcess();
  20305. if (firstPostProcess) {
  20306. firstPostProcess.markTextureDirty();
  20307. }
  20308. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20309. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20310. var cam = this._rigCameras[i];
  20311. var rigPostProcess = cam._rigPostProcess;
  20312. // for VR rig, there does not have to be a post process
  20313. if (rigPostProcess) {
  20314. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20315. if (isPass) {
  20316. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20317. cam.isIntermediate = this._postProcesses.length === 0;
  20318. }
  20319. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20320. rigPostProcess.markTextureDirty();
  20321. }
  20322. else {
  20323. cam._postProcesses = this._postProcesses.slice(0);
  20324. }
  20325. }
  20326. };
  20327. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20328. if (insertAt === void 0) { insertAt = null; }
  20329. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20330. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20331. return 0;
  20332. }
  20333. if (insertAt == null || insertAt < 0) {
  20334. this._postProcesses.push(postProcess);
  20335. }
  20336. else if (this._postProcesses[insertAt] === null) {
  20337. this._postProcesses[insertAt] = postProcess;
  20338. }
  20339. else {
  20340. this._postProcesses.splice(insertAt, 0, postProcess);
  20341. }
  20342. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20343. return this._postProcesses.indexOf(postProcess);
  20344. };
  20345. Camera.prototype.detachPostProcess = function (postProcess) {
  20346. var idx = this._postProcesses.indexOf(postProcess);
  20347. if (idx !== -1) {
  20348. this._postProcesses[idx] = null;
  20349. }
  20350. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20351. };
  20352. Camera.prototype.getWorldMatrix = function () {
  20353. if (!this._worldMatrix) {
  20354. this._worldMatrix = BABYLON.Matrix.Identity();
  20355. }
  20356. var viewMatrix = this.getViewMatrix();
  20357. viewMatrix.invertToRef(this._worldMatrix);
  20358. return this._worldMatrix;
  20359. };
  20360. Camera.prototype._getViewMatrix = function () {
  20361. return BABYLON.Matrix.Identity();
  20362. };
  20363. Camera.prototype.getViewMatrix = function (force) {
  20364. if (!force && this._isSynchronizedViewMatrix()) {
  20365. return this._computedViewMatrix;
  20366. }
  20367. this.updateCache();
  20368. this._computedViewMatrix = this._getViewMatrix();
  20369. this._currentRenderId = this.getScene().getRenderId();
  20370. this._refreshFrustumPlanes = true;
  20371. if (!this.parent || !this.parent.getWorldMatrix) {
  20372. this._globalPosition.copyFrom(this.position);
  20373. }
  20374. else {
  20375. if (!this._worldMatrix) {
  20376. this._worldMatrix = BABYLON.Matrix.Identity();
  20377. }
  20378. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20379. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20380. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20381. this._computedViewMatrix.invert();
  20382. this._markSyncedWithParent();
  20383. }
  20384. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20385. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20386. }
  20387. this.onViewMatrixChangedObservable.notifyObservers(this);
  20388. return this._computedViewMatrix;
  20389. };
  20390. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20391. this._doNotComputeProjectionMatrix = true;
  20392. if (projection !== undefined) {
  20393. this._projectionMatrix = projection;
  20394. }
  20395. };
  20396. ;
  20397. Camera.prototype.unfreezeProjectionMatrix = function () {
  20398. this._doNotComputeProjectionMatrix = false;
  20399. };
  20400. ;
  20401. Camera.prototype.getProjectionMatrix = function (force) {
  20402. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20403. return this._projectionMatrix;
  20404. }
  20405. // Cache
  20406. this._cache.mode = this.mode;
  20407. this._cache.minZ = this.minZ;
  20408. this._cache.maxZ = this.maxZ;
  20409. // Matrix
  20410. this._refreshFrustumPlanes = true;
  20411. var engine = this.getEngine();
  20412. var scene = this.getScene();
  20413. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20414. this._cache.fov = this.fov;
  20415. this._cache.fovMode = this.fovMode;
  20416. this._cache.aspectRatio = engine.getAspectRatio(this);
  20417. if (this.minZ <= 0) {
  20418. this.minZ = 0.1;
  20419. }
  20420. if (scene.useRightHandedSystem) {
  20421. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20422. }
  20423. else {
  20424. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20425. }
  20426. }
  20427. else {
  20428. var halfWidth = engine.getRenderWidth() / 2.0;
  20429. var halfHeight = engine.getRenderHeight() / 2.0;
  20430. if (scene.useRightHandedSystem) {
  20431. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20432. }
  20433. else {
  20434. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20435. }
  20436. this._cache.orthoLeft = this.orthoLeft;
  20437. this._cache.orthoRight = this.orthoRight;
  20438. this._cache.orthoBottom = this.orthoBottom;
  20439. this._cache.orthoTop = this.orthoTop;
  20440. this._cache.renderWidth = engine.getRenderWidth();
  20441. this._cache.renderHeight = engine.getRenderHeight();
  20442. }
  20443. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20444. return this._projectionMatrix;
  20445. };
  20446. Camera.prototype.getTranformationMatrix = function () {
  20447. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20448. return this._transformMatrix;
  20449. };
  20450. Camera.prototype.updateFrustumPlanes = function () {
  20451. if (!this._refreshFrustumPlanes) {
  20452. return;
  20453. }
  20454. this.getTranformationMatrix();
  20455. if (!this._frustumPlanes) {
  20456. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20457. }
  20458. else {
  20459. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20460. }
  20461. this._refreshFrustumPlanes = false;
  20462. };
  20463. Camera.prototype.isInFrustum = function (target) {
  20464. this.updateFrustumPlanes();
  20465. return target.isInFrustum(this._frustumPlanes);
  20466. };
  20467. Camera.prototype.isCompletelyInFrustum = function (target) {
  20468. this.updateFrustumPlanes();
  20469. return target.isCompletelyInFrustum(this._frustumPlanes);
  20470. };
  20471. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20472. if (length === void 0) { length = 100; }
  20473. if (!transform) {
  20474. transform = this.getWorldMatrix();
  20475. }
  20476. if (!origin) {
  20477. origin = this.position;
  20478. }
  20479. var forward = new BABYLON.Vector3(0, 0, 1);
  20480. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20481. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20482. return new BABYLON.Ray(origin, direction, length);
  20483. };
  20484. /**
  20485. * Releases resources associated with this node.
  20486. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20487. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20488. */
  20489. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20490. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20491. // Observables
  20492. this.onViewMatrixChangedObservable.clear();
  20493. this.onProjectionMatrixChangedObservable.clear();
  20494. this.onAfterCheckInputsObservable.clear();
  20495. this.onRestoreStateObservable.clear();
  20496. // Inputs
  20497. if (this.inputs) {
  20498. this.inputs.clear();
  20499. }
  20500. // Animations
  20501. this.getScene().stopAnimation(this);
  20502. // Remove from scene
  20503. this.getScene().removeCamera(this);
  20504. while (this._rigCameras.length > 0) {
  20505. var camera = this._rigCameras.pop();
  20506. if (camera) {
  20507. camera.dispose();
  20508. }
  20509. }
  20510. // Postprocesses
  20511. if (this._rigPostProcess) {
  20512. this._rigPostProcess.dispose(this);
  20513. this._rigPostProcess = null;
  20514. this._postProcesses = [];
  20515. }
  20516. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20517. this._rigPostProcess = null;
  20518. this._postProcesses = [];
  20519. }
  20520. else {
  20521. var i = this._postProcesses.length;
  20522. while (--i >= 0) {
  20523. var postProcess = this._postProcesses[i];
  20524. if (postProcess) {
  20525. postProcess.dispose(this);
  20526. }
  20527. }
  20528. }
  20529. // Render targets
  20530. var i = this.customRenderTargets.length;
  20531. while (--i >= 0) {
  20532. this.customRenderTargets[i].dispose();
  20533. }
  20534. this.customRenderTargets = [];
  20535. // Active Meshes
  20536. this._activeMeshes.dispose();
  20537. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20538. };
  20539. Object.defineProperty(Camera.prototype, "leftCamera", {
  20540. // ---- Camera rigs section ----
  20541. get: function () {
  20542. if (this._rigCameras.length < 1) {
  20543. return null;
  20544. }
  20545. return this._rigCameras[0];
  20546. },
  20547. enumerable: true,
  20548. configurable: true
  20549. });
  20550. Object.defineProperty(Camera.prototype, "rightCamera", {
  20551. get: function () {
  20552. if (this._rigCameras.length < 2) {
  20553. return null;
  20554. }
  20555. return this._rigCameras[1];
  20556. },
  20557. enumerable: true,
  20558. configurable: true
  20559. });
  20560. Camera.prototype.getLeftTarget = function () {
  20561. if (this._rigCameras.length < 1) {
  20562. return null;
  20563. }
  20564. return this._rigCameras[0].getTarget();
  20565. };
  20566. Camera.prototype.getRightTarget = function () {
  20567. if (this._rigCameras.length < 2) {
  20568. return null;
  20569. }
  20570. return this._rigCameras[1].getTarget();
  20571. };
  20572. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20573. if (this.cameraRigMode === mode) {
  20574. return;
  20575. }
  20576. while (this._rigCameras.length > 0) {
  20577. var camera = this._rigCameras.pop();
  20578. if (camera) {
  20579. camera.dispose();
  20580. }
  20581. }
  20582. this.cameraRigMode = mode;
  20583. this._cameraRigParams = {};
  20584. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20585. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20586. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20587. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20588. // create the rig cameras, unless none
  20589. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20590. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20591. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20592. if (leftCamera && rightCamera) {
  20593. this._rigCameras.push(leftCamera);
  20594. this._rigCameras.push(rightCamera);
  20595. }
  20596. }
  20597. switch (this.cameraRigMode) {
  20598. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20599. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20600. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20601. break;
  20602. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20603. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20604. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20605. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20606. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20607. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20608. break;
  20609. case Camera.RIG_MODE_VR:
  20610. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20611. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20612. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20613. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20614. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20615. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20616. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20617. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20618. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20619. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20620. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20621. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20622. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20623. if (metrics.compensateDistortion) {
  20624. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20625. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20626. }
  20627. break;
  20628. case Camera.RIG_MODE_WEBVR:
  20629. if (rigParams.vrDisplay) {
  20630. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20631. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20632. //Left eye
  20633. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20634. this._rigCameras[0].setCameraRigParameter("left", true);
  20635. //leaving this for future reference
  20636. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20637. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20638. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20639. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20640. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20641. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20642. this._rigCameras[0].parent = this;
  20643. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20644. //Right eye
  20645. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20646. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20647. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20648. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20649. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20650. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20651. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20652. this._rigCameras[1].parent = this;
  20653. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20654. if (Camera.UseAlternateWebVRRendering) {
  20655. this._rigCameras[1]._skipRendering = true;
  20656. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20657. }
  20658. }
  20659. break;
  20660. }
  20661. this._cascadePostProcessesToRigCams();
  20662. this.update();
  20663. };
  20664. Camera.prototype._getVRProjectionMatrix = function () {
  20665. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20666. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20667. return this._projectionMatrix;
  20668. };
  20669. Camera.prototype._updateCameraRotationMatrix = function () {
  20670. //Here for WebVR
  20671. };
  20672. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20673. //Here for WebVR
  20674. };
  20675. /**
  20676. * This function MUST be overwritten by the different WebVR cameras available.
  20677. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20678. */
  20679. Camera.prototype._getWebVRProjectionMatrix = function () {
  20680. return BABYLON.Matrix.Identity();
  20681. };
  20682. /**
  20683. * This function MUST be overwritten by the different WebVR cameras available.
  20684. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20685. */
  20686. Camera.prototype._getWebVRViewMatrix = function () {
  20687. return BABYLON.Matrix.Identity();
  20688. };
  20689. Camera.prototype.setCameraRigParameter = function (name, value) {
  20690. if (!this._cameraRigParams) {
  20691. this._cameraRigParams = {};
  20692. }
  20693. this._cameraRigParams[name] = value;
  20694. //provisionnally:
  20695. if (name === "interaxialDistance") {
  20696. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20697. }
  20698. };
  20699. /**
  20700. * needs to be overridden by children so sub has required properties to be copied
  20701. */
  20702. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20703. return null;
  20704. };
  20705. /**
  20706. * May need to be overridden by children
  20707. */
  20708. Camera.prototype._updateRigCameras = function () {
  20709. for (var i = 0; i < this._rigCameras.length; i++) {
  20710. this._rigCameras[i].minZ = this.minZ;
  20711. this._rigCameras[i].maxZ = this.maxZ;
  20712. this._rigCameras[i].fov = this.fov;
  20713. }
  20714. // only update viewport when ANAGLYPH
  20715. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20716. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20717. }
  20718. };
  20719. Camera.prototype._setupInputs = function () {
  20720. };
  20721. Camera.prototype.serialize = function () {
  20722. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20723. // Type
  20724. serializationObject.type = this.getClassName();
  20725. // Parent
  20726. if (this.parent) {
  20727. serializationObject.parentId = this.parent.id;
  20728. }
  20729. if (this.inputs) {
  20730. this.inputs.serialize(serializationObject);
  20731. }
  20732. // Animations
  20733. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20734. serializationObject.ranges = this.serializeAnimationRanges();
  20735. return serializationObject;
  20736. };
  20737. Camera.prototype.clone = function (name) {
  20738. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20739. };
  20740. Camera.prototype.getDirection = function (localAxis) {
  20741. var result = BABYLON.Vector3.Zero();
  20742. this.getDirectionToRef(localAxis, result);
  20743. return result;
  20744. };
  20745. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20746. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20747. };
  20748. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20749. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20750. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20751. switch (type) {
  20752. case "ArcRotateCamera":
  20753. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20754. case "DeviceOrientationCamera":
  20755. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20756. case "FollowCamera":
  20757. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20758. case "ArcFollowCamera":
  20759. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20760. case "GamepadCamera":
  20761. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20762. case "TouchCamera":
  20763. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20764. case "VirtualJoysticksCamera":
  20765. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20766. case "WebVRFreeCamera":
  20767. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20768. case "WebVRGamepadCamera":
  20769. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20770. case "VRDeviceOrientationFreeCamera":
  20771. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20772. case "VRDeviceOrientationGamepadCamera":
  20773. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20774. case "AnaglyphArcRotateCamera":
  20775. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20776. case "AnaglyphFreeCamera":
  20777. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20778. case "AnaglyphGamepadCamera":
  20779. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20780. case "AnaglyphUniversalCamera":
  20781. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20782. case "StereoscopicArcRotateCamera":
  20783. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20784. case "StereoscopicFreeCamera":
  20785. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20786. case "StereoscopicGamepadCamera":
  20787. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20788. case "StereoscopicUniversalCamera":
  20789. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20790. case "FreeCamera":// Forcing Universal here
  20791. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20792. default:// Universal Camera is the default value
  20793. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20794. }
  20795. };
  20796. Camera.prototype.computeWorldMatrix = function () {
  20797. return this.getWorldMatrix();
  20798. };
  20799. Camera.Parse = function (parsedCamera, scene) {
  20800. var type = parsedCamera.type;
  20801. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20802. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20803. // Parent
  20804. if (parsedCamera.parentId) {
  20805. camera._waitingParentId = parsedCamera.parentId;
  20806. }
  20807. //If camera has an input manager, let it parse inputs settings
  20808. if (camera.inputs) {
  20809. camera.inputs.parse(parsedCamera);
  20810. camera._setupInputs();
  20811. }
  20812. if (camera.setPosition) {
  20813. camera.position.copyFromFloats(0, 0, 0);
  20814. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20815. }
  20816. // Target
  20817. if (parsedCamera.target) {
  20818. if (camera.setTarget) {
  20819. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20820. }
  20821. }
  20822. // Apply 3d rig, when found
  20823. if (parsedCamera.cameraRigMode) {
  20824. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20825. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20826. }
  20827. // Animations
  20828. if (parsedCamera.animations) {
  20829. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20830. var parsedAnimation = parsedCamera.animations[animationIndex];
  20831. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20832. }
  20833. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20834. }
  20835. if (parsedCamera.autoAnimate) {
  20836. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20837. }
  20838. return camera;
  20839. };
  20840. // Statics
  20841. Camera._PERSPECTIVE_CAMERA = 0;
  20842. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20843. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20844. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20845. Camera._RIG_MODE_NONE = 0;
  20846. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20847. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20848. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20849. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20850. Camera._RIG_MODE_VR = 20;
  20851. Camera._RIG_MODE_WEBVR = 21;
  20852. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20853. Camera.UseAlternateWebVRRendering = false;
  20854. __decorate([
  20855. BABYLON.serializeAsVector3()
  20856. ], Camera.prototype, "position", void 0);
  20857. __decorate([
  20858. BABYLON.serializeAsVector3()
  20859. ], Camera.prototype, "upVector", void 0);
  20860. __decorate([
  20861. BABYLON.serialize()
  20862. ], Camera.prototype, "orthoLeft", void 0);
  20863. __decorate([
  20864. BABYLON.serialize()
  20865. ], Camera.prototype, "orthoRight", void 0);
  20866. __decorate([
  20867. BABYLON.serialize()
  20868. ], Camera.prototype, "orthoBottom", void 0);
  20869. __decorate([
  20870. BABYLON.serialize()
  20871. ], Camera.prototype, "orthoTop", void 0);
  20872. __decorate([
  20873. BABYLON.serialize()
  20874. ], Camera.prototype, "fov", void 0);
  20875. __decorate([
  20876. BABYLON.serialize()
  20877. ], Camera.prototype, "minZ", void 0);
  20878. __decorate([
  20879. BABYLON.serialize()
  20880. ], Camera.prototype, "maxZ", void 0);
  20881. __decorate([
  20882. BABYLON.serialize()
  20883. ], Camera.prototype, "inertia", void 0);
  20884. __decorate([
  20885. BABYLON.serialize()
  20886. ], Camera.prototype, "mode", void 0);
  20887. __decorate([
  20888. BABYLON.serialize()
  20889. ], Camera.prototype, "layerMask", void 0);
  20890. __decorate([
  20891. BABYLON.serialize()
  20892. ], Camera.prototype, "fovMode", void 0);
  20893. __decorate([
  20894. BABYLON.serialize()
  20895. ], Camera.prototype, "cameraRigMode", void 0);
  20896. __decorate([
  20897. BABYLON.serialize()
  20898. ], Camera.prototype, "interaxialDistance", void 0);
  20899. __decorate([
  20900. BABYLON.serialize()
  20901. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20902. return Camera;
  20903. }(BABYLON.Node));
  20904. BABYLON.Camera = Camera;
  20905. })(BABYLON || (BABYLON = {}));
  20906. //# sourceMappingURL=babylon.camera.js.map
  20907. "use strict";
  20908. var BABYLON;
  20909. (function (BABYLON) {
  20910. var RenderingManager = /** @class */ (function () {
  20911. function RenderingManager(scene) {
  20912. this._renderingGroups = new Array();
  20913. this._autoClearDepthStencil = {};
  20914. this._customOpaqueSortCompareFn = {};
  20915. this._customAlphaTestSortCompareFn = {};
  20916. this._customTransparentSortCompareFn = {};
  20917. this._renderinGroupInfo = null;
  20918. this._scene = scene;
  20919. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20920. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20921. }
  20922. }
  20923. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20924. if (depth === void 0) { depth = true; }
  20925. if (stencil === void 0) { stencil = true; }
  20926. if (this._depthStencilBufferAlreadyCleaned) {
  20927. return;
  20928. }
  20929. this._scene.getEngine().clear(null, false, depth, stencil);
  20930. this._depthStencilBufferAlreadyCleaned = true;
  20931. };
  20932. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20933. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20934. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20935. var info = null;
  20936. if (observable) {
  20937. if (!this._renderinGroupInfo) {
  20938. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20939. }
  20940. info = this._renderinGroupInfo;
  20941. info.scene = this._scene;
  20942. info.camera = this._scene.activeCamera;
  20943. }
  20944. // Dispatch sprites
  20945. if (renderSprites) {
  20946. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20947. var manager = this._scene.spriteManagers[index];
  20948. this.dispatchSprites(manager);
  20949. }
  20950. }
  20951. // Render
  20952. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20953. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20954. var renderingGroup = this._renderingGroups[index];
  20955. if (!renderingGroup && !observable)
  20956. continue;
  20957. var renderingGroupMask = 0;
  20958. // Fire PRECLEAR stage
  20959. if (observable && info) {
  20960. renderingGroupMask = Math.pow(2, index);
  20961. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20962. info.renderingGroupId = index;
  20963. observable.notifyObservers(info, renderingGroupMask);
  20964. }
  20965. // Clear depth/stencil if needed
  20966. if (RenderingManager.AUTOCLEAR) {
  20967. var autoClear = this._autoClearDepthStencil[index];
  20968. if (autoClear && autoClear.autoClear) {
  20969. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20970. }
  20971. }
  20972. if (observable && info) {
  20973. // Fire PREOPAQUE stage
  20974. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20975. observable.notifyObservers(info, renderingGroupMask);
  20976. // Fire PRETRANSPARENT stage
  20977. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20978. observable.notifyObservers(info, renderingGroupMask);
  20979. }
  20980. if (renderingGroup)
  20981. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20982. // Fire POSTTRANSPARENT stage
  20983. if (observable && info) {
  20984. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20985. observable.notifyObservers(info, renderingGroupMask);
  20986. }
  20987. }
  20988. };
  20989. RenderingManager.prototype.reset = function () {
  20990. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20991. var renderingGroup = this._renderingGroups[index];
  20992. if (renderingGroup) {
  20993. renderingGroup.prepare();
  20994. }
  20995. }
  20996. };
  20997. RenderingManager.prototype.dispose = function () {
  20998. this.freeRenderingGroups();
  20999. this._renderingGroups.length = 0;
  21000. };
  21001. /**
  21002. * Clear the info related to rendering groups preventing retention points during dispose.
  21003. */
  21004. RenderingManager.prototype.freeRenderingGroups = function () {
  21005. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21006. var renderingGroup = this._renderingGroups[index];
  21007. if (renderingGroup) {
  21008. renderingGroup.dispose();
  21009. }
  21010. }
  21011. };
  21012. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21013. if (this._renderingGroups[renderingGroupId] === undefined) {
  21014. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21015. }
  21016. };
  21017. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21018. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21019. this._prepareRenderingGroup(renderingGroupId);
  21020. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21021. };
  21022. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21023. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21024. this._prepareRenderingGroup(renderingGroupId);
  21025. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21026. };
  21027. /**
  21028. * @param subMesh The submesh to dispatch
  21029. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21030. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21031. */
  21032. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21033. if (mesh === undefined) {
  21034. mesh = subMesh.getMesh();
  21035. }
  21036. var renderingGroupId = mesh.renderingGroupId || 0;
  21037. this._prepareRenderingGroup(renderingGroupId);
  21038. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21039. };
  21040. /**
  21041. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21042. * This allowed control for front to back rendering or reversly depending of the special needs.
  21043. *
  21044. * @param renderingGroupId The rendering group id corresponding to its index
  21045. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21046. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21047. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21048. */
  21049. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21050. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21051. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21052. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21053. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21054. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21055. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21056. if (this._renderingGroups[renderingGroupId]) {
  21057. var group = this._renderingGroups[renderingGroupId];
  21058. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21059. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21060. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21061. }
  21062. };
  21063. /**
  21064. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21065. *
  21066. * @param renderingGroupId The rendering group id corresponding to its index
  21067. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21068. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21069. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21070. */
  21071. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21072. if (depth === void 0) { depth = true; }
  21073. if (stencil === void 0) { stencil = true; }
  21074. this._autoClearDepthStencil[renderingGroupId] = {
  21075. autoClear: autoClearDepthStencil,
  21076. depth: depth,
  21077. stencil: stencil
  21078. };
  21079. };
  21080. /**
  21081. * The max id used for rendering groups (not included)
  21082. */
  21083. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21084. /**
  21085. * The min id used for rendering groups (included)
  21086. */
  21087. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21088. /**
  21089. * Used to globally prevent autoclearing scenes.
  21090. */
  21091. RenderingManager.AUTOCLEAR = true;
  21092. return RenderingManager;
  21093. }());
  21094. BABYLON.RenderingManager = RenderingManager;
  21095. })(BABYLON || (BABYLON = {}));
  21096. //# sourceMappingURL=babylon.renderingManager.js.map
  21097. "use strict";
  21098. var BABYLON;
  21099. (function (BABYLON) {
  21100. var RenderingGroup = /** @class */ (function () {
  21101. /**
  21102. * Creates a new rendering group.
  21103. * @param index The rendering group index
  21104. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21105. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21106. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21107. */
  21108. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21109. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21110. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21111. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21112. this.index = index;
  21113. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21114. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21115. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21116. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21117. this._particleSystems = new BABYLON.SmartArray(256);
  21118. this._spriteManagers = new BABYLON.SmartArray(256);
  21119. this._edgesRenderers = new BABYLON.SmartArray(16);
  21120. this._scene = scene;
  21121. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21122. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21123. this.transparentSortCompareFn = transparentSortCompareFn;
  21124. }
  21125. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21126. /**
  21127. * Set the opaque sort comparison function.
  21128. * If null the sub meshes will be render in the order they were created
  21129. */
  21130. set: function (value) {
  21131. this._opaqueSortCompareFn = value;
  21132. if (value) {
  21133. this._renderOpaque = this.renderOpaqueSorted;
  21134. }
  21135. else {
  21136. this._renderOpaque = RenderingGroup.renderUnsorted;
  21137. }
  21138. },
  21139. enumerable: true,
  21140. configurable: true
  21141. });
  21142. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21143. /**
  21144. * Set the alpha test sort comparison function.
  21145. * If null the sub meshes will be render in the order they were created
  21146. */
  21147. set: function (value) {
  21148. this._alphaTestSortCompareFn = value;
  21149. if (value) {
  21150. this._renderAlphaTest = this.renderAlphaTestSorted;
  21151. }
  21152. else {
  21153. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21154. }
  21155. },
  21156. enumerable: true,
  21157. configurable: true
  21158. });
  21159. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21160. /**
  21161. * Set the transparent sort comparison function.
  21162. * If null the sub meshes will be render in the order they were created
  21163. */
  21164. set: function (value) {
  21165. if (value) {
  21166. this._transparentSortCompareFn = value;
  21167. }
  21168. else {
  21169. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21170. }
  21171. this._renderTransparent = this.renderTransparentSorted;
  21172. },
  21173. enumerable: true,
  21174. configurable: true
  21175. });
  21176. /**
  21177. * Render all the sub meshes contained in the group.
  21178. * @param customRenderFunction Used to override the default render behaviour of the group.
  21179. * @returns true if rendered some submeshes.
  21180. */
  21181. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21182. if (customRenderFunction) {
  21183. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21184. return;
  21185. }
  21186. var engine = this._scene.getEngine();
  21187. // Depth only
  21188. if (this._depthOnlySubMeshes.length !== 0) {
  21189. engine.setColorWrite(false);
  21190. this._renderAlphaTest(this._depthOnlySubMeshes);
  21191. engine.setColorWrite(true);
  21192. }
  21193. // Opaque
  21194. if (this._opaqueSubMeshes.length !== 0) {
  21195. this._renderOpaque(this._opaqueSubMeshes);
  21196. }
  21197. // Alpha test
  21198. if (this._alphaTestSubMeshes.length !== 0) {
  21199. this._renderAlphaTest(this._alphaTestSubMeshes);
  21200. }
  21201. var stencilState = engine.getStencilBuffer();
  21202. engine.setStencilBuffer(false);
  21203. // Sprites
  21204. if (renderSprites) {
  21205. this._renderSprites();
  21206. }
  21207. // Particles
  21208. if (renderParticles) {
  21209. this._renderParticles(activeMeshes);
  21210. }
  21211. if (this.onBeforeTransparentRendering) {
  21212. this.onBeforeTransparentRendering();
  21213. }
  21214. // Transparent
  21215. if (this._transparentSubMeshes.length !== 0) {
  21216. this._renderTransparent(this._transparentSubMeshes);
  21217. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21218. }
  21219. // Set back stencil to false in case it changes before the edge renderer.
  21220. engine.setStencilBuffer(false);
  21221. // Edges
  21222. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21223. this._edgesRenderers.data[edgesRendererIndex].render();
  21224. }
  21225. // Restore Stencil state.
  21226. engine.setStencilBuffer(stencilState);
  21227. };
  21228. /**
  21229. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21230. * @param subMeshes The submeshes to render
  21231. */
  21232. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21233. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21234. };
  21235. /**
  21236. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21237. * @param subMeshes The submeshes to render
  21238. */
  21239. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21240. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21241. };
  21242. /**
  21243. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21244. * @param subMeshes The submeshes to render
  21245. */
  21246. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21247. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21248. };
  21249. /**
  21250. * Renders the submeshes in a specified order.
  21251. * @param subMeshes The submeshes to sort before render
  21252. * @param sortCompareFn The comparison function use to sort
  21253. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21254. * @param transparent Specifies to activate blending if true
  21255. */
  21256. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21257. var subIndex = 0;
  21258. var subMesh;
  21259. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21260. for (; subIndex < subMeshes.length; subIndex++) {
  21261. subMesh = subMeshes.data[subIndex];
  21262. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21263. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21264. }
  21265. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21266. if (sortCompareFn) {
  21267. sortedArray.sort(sortCompareFn);
  21268. }
  21269. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21270. subMesh = sortedArray[subIndex];
  21271. if (transparent) {
  21272. var material = subMesh.getMaterial();
  21273. if (material && material.needDepthPrePass) {
  21274. var engine = material.getScene().getEngine();
  21275. engine.setColorWrite(false);
  21276. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21277. subMesh.render(false);
  21278. engine.setColorWrite(true);
  21279. }
  21280. }
  21281. subMesh.render(transparent);
  21282. }
  21283. };
  21284. /**
  21285. * Renders the submeshes in the order they were dispatched (no sort applied).
  21286. * @param subMeshes The submeshes to render
  21287. */
  21288. RenderingGroup.renderUnsorted = function (subMeshes) {
  21289. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21290. var submesh = subMeshes.data[subIndex];
  21291. submesh.render(false);
  21292. }
  21293. };
  21294. /**
  21295. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21296. * are rendered back to front if in the same alpha index.
  21297. *
  21298. * @param a The first submesh
  21299. * @param b The second submesh
  21300. * @returns The result of the comparison
  21301. */
  21302. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21303. // Alpha index first
  21304. if (a._alphaIndex > b._alphaIndex) {
  21305. return 1;
  21306. }
  21307. if (a._alphaIndex < b._alphaIndex) {
  21308. return -1;
  21309. }
  21310. // Then distance to camera
  21311. return RenderingGroup.backToFrontSortCompare(a, b);
  21312. };
  21313. /**
  21314. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21315. * are rendered back to front.
  21316. *
  21317. * @param a The first submesh
  21318. * @param b The second submesh
  21319. * @returns The result of the comparison
  21320. */
  21321. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21322. // Then distance to camera
  21323. if (a._distanceToCamera < b._distanceToCamera) {
  21324. return 1;
  21325. }
  21326. if (a._distanceToCamera > b._distanceToCamera) {
  21327. return -1;
  21328. }
  21329. return 0;
  21330. };
  21331. /**
  21332. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21333. * are rendered front to back (prevent overdraw).
  21334. *
  21335. * @param a The first submesh
  21336. * @param b The second submesh
  21337. * @returns The result of the comparison
  21338. */
  21339. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21340. // Then distance to camera
  21341. if (a._distanceToCamera < b._distanceToCamera) {
  21342. return -1;
  21343. }
  21344. if (a._distanceToCamera > b._distanceToCamera) {
  21345. return 1;
  21346. }
  21347. return 0;
  21348. };
  21349. /**
  21350. * Resets the different lists of submeshes to prepare a new frame.
  21351. */
  21352. RenderingGroup.prototype.prepare = function () {
  21353. this._opaqueSubMeshes.reset();
  21354. this._transparentSubMeshes.reset();
  21355. this._alphaTestSubMeshes.reset();
  21356. this._depthOnlySubMeshes.reset();
  21357. this._particleSystems.reset();
  21358. this._spriteManagers.reset();
  21359. this._edgesRenderers.reset();
  21360. };
  21361. RenderingGroup.prototype.dispose = function () {
  21362. this._opaqueSubMeshes.dispose();
  21363. this._transparentSubMeshes.dispose();
  21364. this._alphaTestSubMeshes.dispose();
  21365. this._depthOnlySubMeshes.dispose();
  21366. this._particleSystems.dispose();
  21367. this._spriteManagers.dispose();
  21368. this._edgesRenderers.dispose();
  21369. };
  21370. /**
  21371. * Inserts the submesh in its correct queue depending on its material.
  21372. * @param subMesh The submesh to dispatch
  21373. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21374. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21375. */
  21376. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21377. // Get mesh and materials if not provided
  21378. if (mesh === undefined) {
  21379. mesh = subMesh.getMesh();
  21380. }
  21381. if (material === undefined) {
  21382. material = subMesh.getMaterial();
  21383. }
  21384. if (material === null || material === undefined) {
  21385. return;
  21386. }
  21387. if (material.needAlphaBlendingForMesh(mesh)) {
  21388. this._transparentSubMeshes.push(subMesh);
  21389. }
  21390. else if (material.needAlphaTesting()) {
  21391. if (material.needDepthPrePass) {
  21392. this._depthOnlySubMeshes.push(subMesh);
  21393. }
  21394. this._alphaTestSubMeshes.push(subMesh);
  21395. }
  21396. else {
  21397. if (material.needDepthPrePass) {
  21398. this._depthOnlySubMeshes.push(subMesh);
  21399. }
  21400. this._opaqueSubMeshes.push(subMesh); // Opaque
  21401. }
  21402. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21403. this._edgesRenderers.push(mesh._edgesRenderer);
  21404. }
  21405. };
  21406. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21407. this._spriteManagers.push(spriteManager);
  21408. };
  21409. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21410. this._particleSystems.push(particleSystem);
  21411. };
  21412. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21413. if (this._particleSystems.length === 0) {
  21414. return;
  21415. }
  21416. // Particles
  21417. var activeCamera = this._scene.activeCamera;
  21418. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21419. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21420. var particleSystem = this._particleSystems.data[particleIndex];
  21421. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21422. continue;
  21423. }
  21424. var emitter = particleSystem.emitter;
  21425. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21426. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21427. }
  21428. }
  21429. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21430. };
  21431. RenderingGroup.prototype._renderSprites = function () {
  21432. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21433. return;
  21434. }
  21435. // Sprites
  21436. var activeCamera = this._scene.activeCamera;
  21437. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21438. for (var id = 0; id < this._spriteManagers.length; id++) {
  21439. var spriteManager = this._spriteManagers.data[id];
  21440. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21441. spriteManager.render();
  21442. }
  21443. }
  21444. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21445. };
  21446. return RenderingGroup;
  21447. }());
  21448. BABYLON.RenderingGroup = RenderingGroup;
  21449. })(BABYLON || (BABYLON = {}));
  21450. //# sourceMappingURL=babylon.renderingGroup.js.map
  21451. "use strict";
  21452. var BABYLON;
  21453. (function (BABYLON) {
  21454. var ClickInfo = /** @class */ (function () {
  21455. function ClickInfo() {
  21456. this._singleClick = false;
  21457. this._doubleClick = false;
  21458. this._hasSwiped = false;
  21459. this._ignore = false;
  21460. }
  21461. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21462. get: function () {
  21463. return this._singleClick;
  21464. },
  21465. set: function (b) {
  21466. this._singleClick = b;
  21467. },
  21468. enumerable: true,
  21469. configurable: true
  21470. });
  21471. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21472. get: function () {
  21473. return this._doubleClick;
  21474. },
  21475. set: function (b) {
  21476. this._doubleClick = b;
  21477. },
  21478. enumerable: true,
  21479. configurable: true
  21480. });
  21481. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21482. get: function () {
  21483. return this._hasSwiped;
  21484. },
  21485. set: function (b) {
  21486. this._hasSwiped = b;
  21487. },
  21488. enumerable: true,
  21489. configurable: true
  21490. });
  21491. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21492. get: function () {
  21493. return this._ignore;
  21494. },
  21495. set: function (b) {
  21496. this._ignore = b;
  21497. },
  21498. enumerable: true,
  21499. configurable: true
  21500. });
  21501. return ClickInfo;
  21502. }());
  21503. /**
  21504. * This class is used by the onRenderingGroupObservable
  21505. */
  21506. var RenderingGroupInfo = /** @class */ (function () {
  21507. function RenderingGroupInfo() {
  21508. }
  21509. /**
  21510. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21511. * This stage will be fired no matter what
  21512. */
  21513. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21514. /**
  21515. * Called before opaque object are rendered.
  21516. * This stage will be fired only if there's 3D Opaque content to render
  21517. */
  21518. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21519. /**
  21520. * Called after the opaque objects are rendered and before the transparent ones
  21521. * This stage will be fired only if there's 3D transparent content to render
  21522. */
  21523. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21524. /**
  21525. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21526. * This stage will be fired no matter what
  21527. */
  21528. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21529. return RenderingGroupInfo;
  21530. }());
  21531. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21532. /**
  21533. * Represents a scene to be rendered by the engine.
  21534. * @see http://doc.babylonjs.com/page.php?p=21911
  21535. */
  21536. var Scene = /** @class */ (function () {
  21537. /**
  21538. * @constructor
  21539. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21540. */
  21541. function Scene(engine) {
  21542. // Members
  21543. this.autoClear = true;
  21544. this.autoClearDepthAndStencil = true;
  21545. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21546. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21547. this._forceWireframe = false;
  21548. this._forcePointsCloud = false;
  21549. this.forceShowBoundingBoxes = false;
  21550. this.animationsEnabled = true;
  21551. this.useConstantAnimationDeltaTime = false;
  21552. this.constantlyUpdateMeshUnderPointer = false;
  21553. this.hoverCursor = "pointer";
  21554. this.defaultCursor = "";
  21555. /**
  21556. * This is used to call preventDefault() on pointer down
  21557. * in order to block unwanted artifacts like system double clicks
  21558. */
  21559. this.preventDefaultOnPointerDown = true;
  21560. // Metadata
  21561. this.metadata = null;
  21562. /**
  21563. * An event triggered when the scene is disposed.
  21564. * @type {BABYLON.Observable}
  21565. */
  21566. this.onDisposeObservable = new BABYLON.Observable();
  21567. this._onDisposeObserver = null;
  21568. /**
  21569. * An event triggered before rendering the scene (right after animations and physics)
  21570. * @type {BABYLON.Observable}
  21571. */
  21572. this.onBeforeRenderObservable = new BABYLON.Observable();
  21573. this._onBeforeRenderObserver = null;
  21574. /**
  21575. * An event triggered after rendering the scene
  21576. * @type {BABYLON.Observable}
  21577. */
  21578. this.onAfterRenderObservable = new BABYLON.Observable();
  21579. this._onAfterRenderObserver = null;
  21580. /**
  21581. * An event triggered before animating the scene
  21582. * @type {BABYLON.Observable}
  21583. */
  21584. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21585. /**
  21586. * An event triggered after animations processing
  21587. * @type {BABYLON.Observable}
  21588. */
  21589. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21590. /**
  21591. * An event triggered before draw calls are ready to be sent
  21592. * @type {BABYLON.Observable}
  21593. */
  21594. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21595. /**
  21596. * An event triggered after draw calls have been sent
  21597. * @type {BABYLON.Observable}
  21598. */
  21599. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21600. /**
  21601. * An event triggered when physic simulation is about to be run
  21602. * @type {BABYLON.Observable}
  21603. */
  21604. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21605. /**
  21606. * An event triggered when physic simulation has been done
  21607. * @type {BABYLON.Observable}
  21608. */
  21609. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21610. /**
  21611. * An event triggered when the scene is ready
  21612. * @type {BABYLON.Observable}
  21613. */
  21614. this.onReadyObservable = new BABYLON.Observable();
  21615. /**
  21616. * An event triggered before rendering a camera
  21617. * @type {BABYLON.Observable}
  21618. */
  21619. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21620. this._onBeforeCameraRenderObserver = null;
  21621. /**
  21622. * An event triggered after rendering a camera
  21623. * @type {BABYLON.Observable}
  21624. */
  21625. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21626. this._onAfterCameraRenderObserver = null;
  21627. /**
  21628. * An event triggered when active meshes evaluation is about to start
  21629. * @type {BABYLON.Observable}
  21630. */
  21631. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21632. /**
  21633. * An event triggered when active meshes evaluation is done
  21634. * @type {BABYLON.Observable}
  21635. */
  21636. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21637. /**
  21638. * An event triggered when particles rendering is about to start
  21639. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21640. * @type {BABYLON.Observable}
  21641. */
  21642. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21643. /**
  21644. * An event triggered when particles rendering is done
  21645. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21646. * @type {BABYLON.Observable}
  21647. */
  21648. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21649. /**
  21650. * An event triggered when sprites rendering is about to start
  21651. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21652. * @type {BABYLON.Observable}
  21653. */
  21654. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21655. /**
  21656. * An event triggered when sprites rendering is done
  21657. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21658. * @type {BABYLON.Observable}
  21659. */
  21660. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21661. /**
  21662. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21663. * @type {BABYLON.Observable}
  21664. */
  21665. this.onDataLoadedObservable = new BABYLON.Observable();
  21666. /**
  21667. * An event triggered when a camera is created
  21668. * @type {BABYLON.Observable}
  21669. */
  21670. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21671. /**
  21672. * An event triggered when a camera is removed
  21673. * @type {BABYLON.Observable}
  21674. */
  21675. this.onCameraRemovedObservable = new BABYLON.Observable();
  21676. /**
  21677. * An event triggered when a light is created
  21678. * @type {BABYLON.Observable}
  21679. */
  21680. this.onNewLightAddedObservable = new BABYLON.Observable();
  21681. /**
  21682. * An event triggered when a light is removed
  21683. * @type {BABYLON.Observable}
  21684. */
  21685. this.onLightRemovedObservable = new BABYLON.Observable();
  21686. /**
  21687. * An event triggered when a geometry is created
  21688. * @type {BABYLON.Observable}
  21689. */
  21690. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21691. /**
  21692. * An event triggered when a geometry is removed
  21693. * @type {BABYLON.Observable}
  21694. */
  21695. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21696. /**
  21697. * An event triggered when a transform node is created
  21698. * @type {BABYLON.Observable}
  21699. */
  21700. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21701. /**
  21702. * An event triggered when a transform node is removed
  21703. * @type {BABYLON.Observable}
  21704. */
  21705. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21706. /**
  21707. * An event triggered when a mesh is created
  21708. * @type {BABYLON.Observable}
  21709. */
  21710. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21711. /**
  21712. * An event triggered when a mesh is removed
  21713. * @type {BABYLON.Observable}
  21714. */
  21715. this.onMeshRemovedObservable = new BABYLON.Observable();
  21716. /**
  21717. * An event triggered when render targets are about to be rendered
  21718. * Can happen multiple times per frame.
  21719. * @type {BABYLON.Observable}
  21720. */
  21721. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21722. /**
  21723. * An event triggered when render targets were rendered.
  21724. * Can happen multiple times per frame.
  21725. * @type {BABYLON.Observable}
  21726. */
  21727. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21728. /**
  21729. * An event triggered before calculating deterministic simulation step
  21730. * @type {BABYLON.Observable}
  21731. */
  21732. this.onBeforeStepObservable = new BABYLON.Observable();
  21733. /**
  21734. * An event triggered after calculating deterministic simulation step
  21735. * @type {BABYLON.Observable}
  21736. */
  21737. this.onAfterStepObservable = new BABYLON.Observable();
  21738. /**
  21739. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21740. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21741. * 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)
  21742. */
  21743. this.onRenderingGroupObservable = new BABYLON.Observable();
  21744. // Animations
  21745. this.animations = [];
  21746. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21747. /**
  21748. * 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).
  21749. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21750. */
  21751. this.onPrePointerObservable = new BABYLON.Observable();
  21752. /**
  21753. * Observable event triggered each time an input event is received from the rendering canvas
  21754. */
  21755. this.onPointerObservable = new BABYLON.Observable();
  21756. this._meshPickProceed = false;
  21757. this._currentPickResult = null;
  21758. this._previousPickResult = null;
  21759. this._totalPointersPressed = 0;
  21760. this._doubleClickOccured = false;
  21761. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21762. this.cameraToUseForPointers = null;
  21763. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21764. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21765. this._startingPointerTime = 0;
  21766. this._previousStartingPointerTime = 0;
  21767. // Deterministic lockstep
  21768. this._timeAccumulator = 0;
  21769. this._currentStepId = 0;
  21770. this._currentInternalStep = 0;
  21771. // Keyboard
  21772. /**
  21773. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21774. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21775. */
  21776. this.onPreKeyboardObservable = new BABYLON.Observable();
  21777. /**
  21778. * Observable event triggered each time an keyboard event is received from the hosting window
  21779. */
  21780. this.onKeyboardObservable = new BABYLON.Observable();
  21781. // Coordinate system
  21782. /**
  21783. * use right-handed coordinate system on this scene.
  21784. * @type {boolean}
  21785. */
  21786. this._useRightHandedSystem = false;
  21787. // Fog
  21788. this._fogEnabled = true;
  21789. this._fogMode = Scene.FOGMODE_NONE;
  21790. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21791. this.fogDensity = 0.1;
  21792. this.fogStart = 0;
  21793. this.fogEnd = 1000.0;
  21794. // Lights
  21795. /**
  21796. * is shadow enabled on this scene.
  21797. * @type {boolean}
  21798. */
  21799. this._shadowsEnabled = true;
  21800. /**
  21801. * is light enabled on this scene.
  21802. * @type {boolean}
  21803. */
  21804. this._lightsEnabled = true;
  21805. /**
  21806. * All of the lights added to this scene.
  21807. * @see BABYLON.Light
  21808. * @type {BABYLON.Light[]}
  21809. */
  21810. this.lights = new Array();
  21811. // Cameras
  21812. /** All of the cameras added to this scene. */
  21813. this.cameras = new Array();
  21814. /** All of the active cameras added to this scene. */
  21815. this.activeCameras = new Array();
  21816. // Meshes
  21817. /**
  21818. * All of the tranform nodes added to this scene.
  21819. * @see BABYLON.TransformNode
  21820. * @type {BABYLON.TransformNode[]}
  21821. */
  21822. this.transformNodes = new Array();
  21823. /**
  21824. * All of the (abstract) meshes added to this scene.
  21825. * @see BABYLON.AbstractMesh
  21826. * @type {BABYLON.AbstractMesh[]}
  21827. */
  21828. this.meshes = new Array();
  21829. /**
  21830. * All of the animation groups added to this scene.
  21831. * @see BABYLON.AnimationGroup
  21832. * @type {BABYLON.AnimationGroup[]}
  21833. */
  21834. this.animationGroups = new Array();
  21835. // Geometries
  21836. this._geometries = new Array();
  21837. this.materials = new Array();
  21838. this.multiMaterials = new Array();
  21839. // Textures
  21840. this._texturesEnabled = true;
  21841. this.textures = new Array();
  21842. // Particles
  21843. this.particlesEnabled = true;
  21844. this.particleSystems = new Array();
  21845. // Sprites
  21846. this.spritesEnabled = true;
  21847. this.spriteManagers = new Array();
  21848. /**
  21849. * The list of layers (background and foreground) of the scene.
  21850. */
  21851. this.layers = new Array();
  21852. /**
  21853. * The list of effect layers (highlights/glow) contained in the scene.
  21854. */
  21855. this.effectLayers = new Array();
  21856. // Skeletons
  21857. this._skeletonsEnabled = true;
  21858. this.skeletons = new Array();
  21859. // Morph targets
  21860. this.morphTargetManagers = new Array();
  21861. // Lens flares
  21862. this.lensFlaresEnabled = true;
  21863. this.lensFlareSystems = new Array();
  21864. // Collisions
  21865. this.collisionsEnabled = true;
  21866. /** Defines the gravity applied to this scene */
  21867. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21868. // Postprocesses
  21869. this.postProcesses = new Array();
  21870. this.postProcessesEnabled = true;
  21871. // Customs render targets
  21872. this.renderTargetsEnabled = true;
  21873. this.dumpNextRenderTargets = false;
  21874. this.customRenderTargets = new Array();
  21875. // Imported meshes
  21876. this.importedMeshesFiles = new Array();
  21877. // Probes
  21878. this.probesEnabled = true;
  21879. this.reflectionProbes = new Array();
  21880. this._actionManagers = new Array();
  21881. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21882. // Procedural textures
  21883. this.proceduralTexturesEnabled = true;
  21884. this._proceduralTextures = new Array();
  21885. this.soundTracks = new Array();
  21886. this._audioEnabled = true;
  21887. this._headphone = false;
  21888. // Performance counters
  21889. this._totalVertices = new BABYLON.PerfCounter();
  21890. this._activeIndices = new BABYLON.PerfCounter();
  21891. this._activeParticles = new BABYLON.PerfCounter();
  21892. this._activeBones = new BABYLON.PerfCounter();
  21893. this._animationTime = 0;
  21894. this.animationTimeScale = 1;
  21895. this._renderId = 0;
  21896. this._executeWhenReadyTimeoutId = -1;
  21897. this._intermediateRendering = false;
  21898. this._viewUpdateFlag = -1;
  21899. this._projectionUpdateFlag = -1;
  21900. this._alternateViewUpdateFlag = -1;
  21901. this._alternateProjectionUpdateFlag = -1;
  21902. this._toBeDisposed = new BABYLON.SmartArray(256);
  21903. this._activeRequests = new Array();
  21904. this._pendingData = new Array();
  21905. this._isDisposed = false;
  21906. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21907. this._activeMeshes = new BABYLON.SmartArray(256);
  21908. this._processedMaterials = new BABYLON.SmartArray(256);
  21909. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21910. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21911. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21912. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21913. this._activeAnimatables = new Array();
  21914. this._transformMatrix = BABYLON.Matrix.Zero();
  21915. this._useAlternateCameraConfiguration = false;
  21916. this._alternateRendering = false;
  21917. this.requireLightSorting = false;
  21918. this._depthRenderer = {};
  21919. this._activeMeshesFrozen = false;
  21920. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21921. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21922. this._engine.scenes.push(this);
  21923. this._uid = null;
  21924. this._renderingManager = new BABYLON.RenderingManager(this);
  21925. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21926. if (BABYLON.OutlineRenderer) {
  21927. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21928. }
  21929. if (BABYLON.Tools.IsWindowObjectExist()) {
  21930. this.attachControl();
  21931. }
  21932. //simplification queue
  21933. if (BABYLON.SimplificationQueue) {
  21934. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21935. }
  21936. //collision coordinator initialization. For now legacy per default.
  21937. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21938. // Uniform Buffer
  21939. this._createUbo();
  21940. // Default Image processing definition.
  21941. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21942. }
  21943. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21944. /** The fog is deactivated */
  21945. get: function () {
  21946. return Scene._FOGMODE_NONE;
  21947. },
  21948. enumerable: true,
  21949. configurable: true
  21950. });
  21951. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21952. /** The fog density is following an exponential function */
  21953. get: function () {
  21954. return Scene._FOGMODE_EXP;
  21955. },
  21956. enumerable: true,
  21957. configurable: true
  21958. });
  21959. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21960. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21961. get: function () {
  21962. return Scene._FOGMODE_EXP2;
  21963. },
  21964. enumerable: true,
  21965. configurable: true
  21966. });
  21967. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21968. /** The fog density is following a linear function. */
  21969. get: function () {
  21970. return Scene._FOGMODE_LINEAR;
  21971. },
  21972. enumerable: true,
  21973. configurable: true
  21974. });
  21975. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21976. /**
  21977. * Texture used in all pbr material as the reflection texture.
  21978. * As in the majority of the scene they are the same (exception for multi room and so on),
  21979. * this is easier to reference from here than from all the materials.
  21980. */
  21981. get: function () {
  21982. return this._environmentTexture;
  21983. },
  21984. /**
  21985. * Texture used in all pbr material as the reflection texture.
  21986. * As in the majority of the scene they are the same (exception for multi room and so on),
  21987. * this is easier to set here than in all the materials.
  21988. */
  21989. set: function (value) {
  21990. if (this._environmentTexture === value) {
  21991. return;
  21992. }
  21993. this._environmentTexture = value;
  21994. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21995. },
  21996. enumerable: true,
  21997. configurable: true
  21998. });
  21999. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22000. /**
  22001. * Default image processing configuration used either in the rendering
  22002. * Forward main pass or through the imageProcessingPostProcess if present.
  22003. * As in the majority of the scene they are the same (exception for multi camera),
  22004. * this is easier to reference from here than from all the materials and post process.
  22005. *
  22006. * No setter as we it is a shared configuration, you can set the values instead.
  22007. */
  22008. get: function () {
  22009. return this._imageProcessingConfiguration;
  22010. },
  22011. enumerable: true,
  22012. configurable: true
  22013. });
  22014. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22015. get: function () {
  22016. return this._forceWireframe;
  22017. },
  22018. set: function (value) {
  22019. if (this._forceWireframe === value) {
  22020. return;
  22021. }
  22022. this._forceWireframe = value;
  22023. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22024. },
  22025. enumerable: true,
  22026. configurable: true
  22027. });
  22028. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22029. get: function () {
  22030. return this._forcePointsCloud;
  22031. },
  22032. set: function (value) {
  22033. if (this._forcePointsCloud === value) {
  22034. return;
  22035. }
  22036. this._forcePointsCloud = value;
  22037. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22038. },
  22039. enumerable: true,
  22040. configurable: true
  22041. });
  22042. Object.defineProperty(Scene.prototype, "onDispose", {
  22043. /** A function to be executed when this scene is disposed. */
  22044. set: function (callback) {
  22045. if (this._onDisposeObserver) {
  22046. this.onDisposeObservable.remove(this._onDisposeObserver);
  22047. }
  22048. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22049. },
  22050. enumerable: true,
  22051. configurable: true
  22052. });
  22053. Object.defineProperty(Scene.prototype, "beforeRender", {
  22054. /** A function to be executed before rendering this scene */
  22055. set: function (callback) {
  22056. if (this._onBeforeRenderObserver) {
  22057. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22058. }
  22059. if (callback) {
  22060. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22061. }
  22062. },
  22063. enumerable: true,
  22064. configurable: true
  22065. });
  22066. Object.defineProperty(Scene.prototype, "afterRender", {
  22067. /** A function to be executed after rendering this scene */
  22068. set: function (callback) {
  22069. if (this._onAfterRenderObserver) {
  22070. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22071. }
  22072. if (callback) {
  22073. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22074. }
  22075. },
  22076. enumerable: true,
  22077. configurable: true
  22078. });
  22079. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22080. set: function (callback) {
  22081. if (this._onBeforeCameraRenderObserver) {
  22082. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22083. }
  22084. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22085. },
  22086. enumerable: true,
  22087. configurable: true
  22088. });
  22089. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22090. set: function (callback) {
  22091. if (this._onAfterCameraRenderObserver) {
  22092. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22093. }
  22094. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22095. },
  22096. enumerable: true,
  22097. configurable: true
  22098. });
  22099. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22100. get: function () {
  22101. if (!this._gamepadManager) {
  22102. this._gamepadManager = new BABYLON.GamepadManager(this);
  22103. }
  22104. return this._gamepadManager;
  22105. },
  22106. enumerable: true,
  22107. configurable: true
  22108. });
  22109. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22110. get: function () {
  22111. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22112. },
  22113. enumerable: true,
  22114. configurable: true
  22115. });
  22116. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22117. get: function () {
  22118. return this._useRightHandedSystem;
  22119. },
  22120. set: function (value) {
  22121. if (this._useRightHandedSystem === value) {
  22122. return;
  22123. }
  22124. this._useRightHandedSystem = value;
  22125. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22126. },
  22127. enumerable: true,
  22128. configurable: true
  22129. });
  22130. Scene.prototype.setStepId = function (newStepId) {
  22131. this._currentStepId = newStepId;
  22132. };
  22133. ;
  22134. Scene.prototype.getStepId = function () {
  22135. return this._currentStepId;
  22136. };
  22137. ;
  22138. Scene.prototype.getInternalStep = function () {
  22139. return this._currentInternalStep;
  22140. };
  22141. ;
  22142. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22143. get: function () {
  22144. return this._fogEnabled;
  22145. },
  22146. /**
  22147. * is fog enabled on this scene.
  22148. */
  22149. set: function (value) {
  22150. if (this._fogEnabled === value) {
  22151. return;
  22152. }
  22153. this._fogEnabled = value;
  22154. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22155. },
  22156. enumerable: true,
  22157. configurable: true
  22158. });
  22159. Object.defineProperty(Scene.prototype, "fogMode", {
  22160. get: function () {
  22161. return this._fogMode;
  22162. },
  22163. set: function (value) {
  22164. if (this._fogMode === value) {
  22165. return;
  22166. }
  22167. this._fogMode = value;
  22168. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22169. },
  22170. enumerable: true,
  22171. configurable: true
  22172. });
  22173. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22174. get: function () {
  22175. return this._shadowsEnabled;
  22176. },
  22177. set: function (value) {
  22178. if (this._shadowsEnabled === value) {
  22179. return;
  22180. }
  22181. this._shadowsEnabled = value;
  22182. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22183. },
  22184. enumerable: true,
  22185. configurable: true
  22186. });
  22187. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22188. get: function () {
  22189. return this._lightsEnabled;
  22190. },
  22191. set: function (value) {
  22192. if (this._lightsEnabled === value) {
  22193. return;
  22194. }
  22195. this._lightsEnabled = value;
  22196. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22197. },
  22198. enumerable: true,
  22199. configurable: true
  22200. });
  22201. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22202. /** The default material used on meshes when no material is affected */
  22203. get: function () {
  22204. if (!this._defaultMaterial) {
  22205. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22206. }
  22207. return this._defaultMaterial;
  22208. },
  22209. /** The default material used on meshes when no material is affected */
  22210. set: function (value) {
  22211. this._defaultMaterial = value;
  22212. },
  22213. enumerable: true,
  22214. configurable: true
  22215. });
  22216. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22217. get: function () {
  22218. return this._texturesEnabled;
  22219. },
  22220. set: function (value) {
  22221. if (this._texturesEnabled === value) {
  22222. return;
  22223. }
  22224. this._texturesEnabled = value;
  22225. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22226. },
  22227. enumerable: true,
  22228. configurable: true
  22229. });
  22230. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22231. get: function () {
  22232. return this._skeletonsEnabled;
  22233. },
  22234. set: function (value) {
  22235. if (this._skeletonsEnabled === value) {
  22236. return;
  22237. }
  22238. this._skeletonsEnabled = value;
  22239. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22240. },
  22241. enumerable: true,
  22242. configurable: true
  22243. });
  22244. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22245. get: function () {
  22246. if (!this._postProcessRenderPipelineManager) {
  22247. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22248. }
  22249. return this._postProcessRenderPipelineManager;
  22250. },
  22251. enumerable: true,
  22252. configurable: true
  22253. });
  22254. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22255. get: function () {
  22256. if (!this._mainSoundTrack) {
  22257. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22258. }
  22259. return this._mainSoundTrack;
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22265. get: function () {
  22266. return this._alternateRendering;
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22272. get: function () {
  22273. return this._frustumPlanes;
  22274. },
  22275. enumerable: true,
  22276. configurable: true
  22277. });
  22278. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22279. /**
  22280. * Gets the current geometry buffer associated to the scene.
  22281. */
  22282. get: function () {
  22283. return this._geometryBufferRenderer;
  22284. },
  22285. /**
  22286. * Sets the current geometry buffer for the scene.
  22287. */
  22288. set: function (geometryBufferRenderer) {
  22289. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22290. this._geometryBufferRenderer = geometryBufferRenderer;
  22291. }
  22292. },
  22293. enumerable: true,
  22294. configurable: true
  22295. });
  22296. Object.defineProperty(Scene.prototype, "debugLayer", {
  22297. // Properties
  22298. get: function () {
  22299. if (!this._debugLayer) {
  22300. this._debugLayer = new BABYLON.DebugLayer(this);
  22301. }
  22302. return this._debugLayer;
  22303. },
  22304. enumerable: true,
  22305. configurable: true
  22306. });
  22307. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22308. get: function () {
  22309. return this._workerCollisions;
  22310. },
  22311. set: function (enabled) {
  22312. if (!BABYLON.CollisionCoordinatorLegacy) {
  22313. return;
  22314. }
  22315. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22316. this._workerCollisions = enabled;
  22317. if (this.collisionCoordinator) {
  22318. this.collisionCoordinator.destroy();
  22319. }
  22320. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22321. this.collisionCoordinator.init(this);
  22322. },
  22323. enumerable: true,
  22324. configurable: true
  22325. });
  22326. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22327. get: function () {
  22328. return this._selectionOctree;
  22329. },
  22330. enumerable: true,
  22331. configurable: true
  22332. });
  22333. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22334. /**
  22335. * The mesh that is currently under the pointer.
  22336. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22337. */
  22338. get: function () {
  22339. return this._pointerOverMesh;
  22340. },
  22341. enumerable: true,
  22342. configurable: true
  22343. });
  22344. Object.defineProperty(Scene.prototype, "pointerX", {
  22345. /**
  22346. * Current on-screen X position of the pointer
  22347. * @return {number} X position of the pointer
  22348. */
  22349. get: function () {
  22350. return this._pointerX;
  22351. },
  22352. enumerable: true,
  22353. configurable: true
  22354. });
  22355. Object.defineProperty(Scene.prototype, "pointerY", {
  22356. /**
  22357. * Current on-screen Y position of the pointer
  22358. * @return {number} Y position of the pointer
  22359. */
  22360. get: function () {
  22361. return this._pointerY;
  22362. },
  22363. enumerable: true,
  22364. configurable: true
  22365. });
  22366. Scene.prototype.getCachedMaterial = function () {
  22367. return this._cachedMaterial;
  22368. };
  22369. Scene.prototype.getCachedEffect = function () {
  22370. return this._cachedEffect;
  22371. };
  22372. Scene.prototype.getCachedVisibility = function () {
  22373. return this._cachedVisibility;
  22374. };
  22375. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22376. if (visibility === void 0) { visibility = 1; }
  22377. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22378. };
  22379. Scene.prototype.getBoundingBoxRenderer = function () {
  22380. if (!this._boundingBoxRenderer) {
  22381. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22382. }
  22383. return this._boundingBoxRenderer;
  22384. };
  22385. Scene.prototype.getOutlineRenderer = function () {
  22386. return this._outlineRenderer;
  22387. };
  22388. Scene.prototype.getEngine = function () {
  22389. return this._engine;
  22390. };
  22391. Scene.prototype.getTotalVertices = function () {
  22392. return this._totalVertices.current;
  22393. };
  22394. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22395. get: function () {
  22396. return this._totalVertices;
  22397. },
  22398. enumerable: true,
  22399. configurable: true
  22400. });
  22401. Scene.prototype.getActiveIndices = function () {
  22402. return this._activeIndices.current;
  22403. };
  22404. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22405. get: function () {
  22406. return this._activeIndices;
  22407. },
  22408. enumerable: true,
  22409. configurable: true
  22410. });
  22411. Scene.prototype.getActiveParticles = function () {
  22412. return this._activeParticles.current;
  22413. };
  22414. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22415. get: function () {
  22416. return this._activeParticles;
  22417. },
  22418. enumerable: true,
  22419. configurable: true
  22420. });
  22421. Scene.prototype.getActiveBones = function () {
  22422. return this._activeBones.current;
  22423. };
  22424. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22425. get: function () {
  22426. return this._activeBones;
  22427. },
  22428. enumerable: true,
  22429. configurable: true
  22430. });
  22431. // Stats
  22432. Scene.prototype.getInterFramePerfCounter = function () {
  22433. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22434. return 0;
  22435. };
  22436. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22437. get: function () {
  22438. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22439. return null;
  22440. },
  22441. enumerable: true,
  22442. configurable: true
  22443. });
  22444. Scene.prototype.getLastFrameDuration = function () {
  22445. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22446. return 0;
  22447. };
  22448. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22449. get: function () {
  22450. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22451. return null;
  22452. },
  22453. enumerable: true,
  22454. configurable: true
  22455. });
  22456. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22457. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22458. return 0;
  22459. };
  22460. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22461. get: function () {
  22462. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22463. return null;
  22464. },
  22465. enumerable: true,
  22466. configurable: true
  22467. });
  22468. Scene.prototype.getActiveMeshes = function () {
  22469. return this._activeMeshes;
  22470. };
  22471. Scene.prototype.getRenderTargetsDuration = function () {
  22472. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22473. return 0;
  22474. };
  22475. Scene.prototype.getRenderDuration = function () {
  22476. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22477. return 0;
  22478. };
  22479. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22480. get: function () {
  22481. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22482. return null;
  22483. },
  22484. enumerable: true,
  22485. configurable: true
  22486. });
  22487. Scene.prototype.getParticlesDuration = function () {
  22488. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22489. return 0;
  22490. };
  22491. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22492. get: function () {
  22493. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22494. return null;
  22495. },
  22496. enumerable: true,
  22497. configurable: true
  22498. });
  22499. Scene.prototype.getSpritesDuration = function () {
  22500. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22501. return 0;
  22502. };
  22503. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22504. get: function () {
  22505. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22506. return null;
  22507. },
  22508. enumerable: true,
  22509. configurable: true
  22510. });
  22511. Scene.prototype.getAnimationRatio = function () {
  22512. return this._animationRatio;
  22513. };
  22514. Scene.prototype.getRenderId = function () {
  22515. return this._renderId;
  22516. };
  22517. Scene.prototype.incrementRenderId = function () {
  22518. this._renderId++;
  22519. };
  22520. Scene.prototype._updatePointerPosition = function (evt) {
  22521. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22522. if (!canvasRect) {
  22523. return;
  22524. }
  22525. this._pointerX = evt.clientX - canvasRect.left;
  22526. this._pointerY = evt.clientY - canvasRect.top;
  22527. this._unTranslatedPointerX = this._pointerX;
  22528. this._unTranslatedPointerY = this._pointerY;
  22529. };
  22530. Scene.prototype._createUbo = function () {
  22531. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22532. this._sceneUbo.addUniform("viewProjection", 16);
  22533. this._sceneUbo.addUniform("view", 16);
  22534. };
  22535. Scene.prototype._createAlternateUbo = function () {
  22536. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22537. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22538. this._alternateSceneUbo.addUniform("view", 16);
  22539. };
  22540. // Pointers handling
  22541. /**
  22542. * Use this method to simulate a pointer move on a mesh
  22543. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22544. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22545. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22546. */
  22547. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22548. var evt = new PointerEvent("pointermove", pointerEventInit);
  22549. return this._processPointerMove(pickResult, evt);
  22550. };
  22551. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22552. var canvas = this._engine.getRenderingCanvas();
  22553. if (!canvas) {
  22554. return this;
  22555. }
  22556. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22557. this.setPointerOverSprite(null);
  22558. this.setPointerOverMesh(pickResult.pickedMesh);
  22559. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22560. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22561. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22562. }
  22563. else {
  22564. canvas.style.cursor = this.hoverCursor;
  22565. }
  22566. }
  22567. else {
  22568. canvas.style.cursor = this.defaultCursor;
  22569. }
  22570. }
  22571. else {
  22572. this.setPointerOverMesh(null);
  22573. // Sprites
  22574. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22575. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22576. this.setPointerOverSprite(pickResult.pickedSprite);
  22577. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22578. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22579. }
  22580. else {
  22581. canvas.style.cursor = this.hoverCursor;
  22582. }
  22583. }
  22584. else {
  22585. this.setPointerOverSprite(null);
  22586. // Restore pointer
  22587. canvas.style.cursor = this.defaultCursor;
  22588. }
  22589. }
  22590. if (pickResult) {
  22591. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22592. if (this.onPointerMove) {
  22593. this.onPointerMove(evt, pickResult, type);
  22594. }
  22595. if (this.onPointerObservable.hasObservers()) {
  22596. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22597. this.onPointerObservable.notifyObservers(pi, type);
  22598. }
  22599. }
  22600. return this;
  22601. };
  22602. /**
  22603. * Use this method to simulate a pointer down on a mesh
  22604. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22605. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22606. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22607. */
  22608. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22609. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22610. return this._processPointerDown(pickResult, evt);
  22611. };
  22612. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22613. var _this = this;
  22614. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22615. this._pickedDownMesh = pickResult.pickedMesh;
  22616. var actionManager = pickResult.pickedMesh.actionManager;
  22617. if (actionManager) {
  22618. if (actionManager.hasPickTriggers) {
  22619. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22620. switch (evt.button) {
  22621. case 0:
  22622. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22623. break;
  22624. case 1:
  22625. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22626. break;
  22627. case 2:
  22628. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22629. break;
  22630. }
  22631. }
  22632. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22633. window.setTimeout(function () {
  22634. 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);
  22635. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22636. if (_this._totalPointersPressed !== 0 &&
  22637. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22638. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22639. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22640. _this._startingPointerTime = 0;
  22641. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22642. }
  22643. }
  22644. }, Scene.LongPressDelay);
  22645. }
  22646. }
  22647. }
  22648. if (pickResult) {
  22649. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22650. if (this.onPointerDown) {
  22651. this.onPointerDown(evt, pickResult, type);
  22652. }
  22653. if (this.onPointerObservable.hasObservers()) {
  22654. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22655. this.onPointerObservable.notifyObservers(pi, type);
  22656. }
  22657. }
  22658. return this;
  22659. };
  22660. /**
  22661. * Use this method to simulate a pointer up on a mesh
  22662. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22663. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22664. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22665. */
  22666. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22667. var evt = new PointerEvent("pointerup", pointerEventInit);
  22668. var clickInfo = new ClickInfo();
  22669. clickInfo.singleClick = true;
  22670. clickInfo.ignore = true;
  22671. return this._processPointerUp(pickResult, evt, clickInfo);
  22672. };
  22673. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22674. if (pickResult && pickResult && pickResult.pickedMesh) {
  22675. this._pickedUpMesh = pickResult.pickedMesh;
  22676. if (this._pickedDownMesh === this._pickedUpMesh) {
  22677. if (this.onPointerPick) {
  22678. this.onPointerPick(evt, pickResult);
  22679. }
  22680. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22681. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22682. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22683. this.onPointerObservable.notifyObservers(pi, type_1);
  22684. }
  22685. }
  22686. if (pickResult.pickedMesh.actionManager) {
  22687. if (clickInfo.ignore) {
  22688. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22689. }
  22690. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22691. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22692. }
  22693. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22694. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22695. }
  22696. }
  22697. }
  22698. if (this._pickedDownMesh &&
  22699. this._pickedDownMesh.actionManager &&
  22700. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22701. this._pickedDownMesh !== this._pickedUpMesh) {
  22702. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22703. }
  22704. var type = BABYLON.PointerEventTypes.POINTERUP;
  22705. if (this.onPointerObservable.hasObservers()) {
  22706. if (!clickInfo.ignore) {
  22707. if (!clickInfo.hasSwiped) {
  22708. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22709. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22710. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22711. this.onPointerObservable.notifyObservers(pi, type_2);
  22712. }
  22713. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22714. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22715. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22716. this.onPointerObservable.notifyObservers(pi, type_3);
  22717. }
  22718. }
  22719. }
  22720. else {
  22721. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22722. this.onPointerObservable.notifyObservers(pi, type);
  22723. }
  22724. }
  22725. if (this.onPointerUp) {
  22726. this.onPointerUp(evt, pickResult, type);
  22727. }
  22728. return this;
  22729. };
  22730. /**
  22731. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22732. * @param attachUp defines if you want to attach events to pointerup
  22733. * @param attachDown defines if you want to attach events to pointerdown
  22734. * @param attachMove defines if you want to attach events to pointermove
  22735. */
  22736. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22737. var _this = this;
  22738. if (attachUp === void 0) { attachUp = true; }
  22739. if (attachDown === void 0) { attachDown = true; }
  22740. if (attachMove === void 0) { attachMove = true; }
  22741. this._initActionManager = function (act, clickInfo) {
  22742. if (!_this._meshPickProceed) {
  22743. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22744. _this._currentPickResult = pickResult;
  22745. if (pickResult) {
  22746. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22747. }
  22748. _this._meshPickProceed = true;
  22749. }
  22750. return act;
  22751. };
  22752. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22753. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22754. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22755. btn !== _this._previousButtonPressed) {
  22756. _this._doubleClickOccured = false;
  22757. clickInfo.singleClick = true;
  22758. clickInfo.ignore = false;
  22759. cb(clickInfo, _this._currentPickResult);
  22760. }
  22761. };
  22762. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22763. var clickInfo = new ClickInfo();
  22764. _this._currentPickResult = null;
  22765. var act = null;
  22766. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22767. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22768. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22769. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22770. act = _this._initActionManager(act, clickInfo);
  22771. if (act)
  22772. checkPicking = act.hasPickTriggers;
  22773. }
  22774. if (checkPicking) {
  22775. var btn = evt.button;
  22776. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22777. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22778. if (!clickInfo.hasSwiped) {
  22779. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22780. if (!checkSingleClickImmediately) {
  22781. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22782. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22783. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22784. act = _this._initActionManager(act, clickInfo);
  22785. if (act)
  22786. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22787. }
  22788. }
  22789. if (checkSingleClickImmediately) {
  22790. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22791. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22792. btn !== _this._previousButtonPressed) {
  22793. clickInfo.singleClick = true;
  22794. cb(clickInfo, _this._currentPickResult);
  22795. }
  22796. }
  22797. else {
  22798. // wait that no double click has been raised during the double click delay
  22799. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22800. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22801. }
  22802. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22803. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22804. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22805. act = _this._initActionManager(act, clickInfo);
  22806. if (act)
  22807. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22808. }
  22809. if (checkDoubleClick) {
  22810. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22811. if (btn === _this._previousButtonPressed &&
  22812. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22813. !_this._doubleClickOccured) {
  22814. // pointer has not moved for 2 clicks, it's a double click
  22815. if (!clickInfo.hasSwiped &&
  22816. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22817. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22818. _this._previousStartingPointerTime = 0;
  22819. _this._doubleClickOccured = true;
  22820. clickInfo.doubleClick = true;
  22821. clickInfo.ignore = false;
  22822. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22823. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22824. }
  22825. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22826. cb(clickInfo, _this._currentPickResult);
  22827. }
  22828. else {
  22829. _this._doubleClickOccured = false;
  22830. _this._previousStartingPointerTime = _this._startingPointerTime;
  22831. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22832. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22833. _this._previousButtonPressed = btn;
  22834. if (Scene.ExclusiveDoubleClickMode) {
  22835. if (_this._previousDelayedSimpleClickTimeout) {
  22836. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22837. }
  22838. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22839. cb(clickInfo, _this._previousPickResult);
  22840. }
  22841. else {
  22842. cb(clickInfo, _this._currentPickResult);
  22843. }
  22844. }
  22845. }
  22846. else {
  22847. _this._doubleClickOccured = false;
  22848. _this._previousStartingPointerTime = _this._startingPointerTime;
  22849. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22850. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22851. _this._previousButtonPressed = btn;
  22852. }
  22853. }
  22854. }
  22855. }
  22856. clickInfo.ignore = true;
  22857. cb(clickInfo, _this._currentPickResult);
  22858. };
  22859. this._spritePredicate = function (sprite) {
  22860. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22861. };
  22862. this._onPointerMove = function (evt) {
  22863. _this._updatePointerPosition(evt);
  22864. // PreObservable support
  22865. if (_this.onPrePointerObservable.hasObservers()) {
  22866. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22867. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22868. _this.onPrePointerObservable.notifyObservers(pi, type);
  22869. if (pi.skipOnPointerObservable) {
  22870. return;
  22871. }
  22872. }
  22873. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22874. return;
  22875. }
  22876. if (!_this.pointerMovePredicate) {
  22877. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22878. }
  22879. // Meshes
  22880. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22881. _this._processPointerMove(pickResult, evt);
  22882. };
  22883. this._onPointerDown = function (evt) {
  22884. _this._totalPointersPressed++;
  22885. _this._pickedDownMesh = null;
  22886. _this._meshPickProceed = false;
  22887. _this._updatePointerPosition(evt);
  22888. if (_this.preventDefaultOnPointerDown && canvas) {
  22889. evt.preventDefault();
  22890. canvas.focus();
  22891. }
  22892. // PreObservable support
  22893. if (_this.onPrePointerObservable.hasObservers()) {
  22894. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22895. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22896. _this.onPrePointerObservable.notifyObservers(pi, type);
  22897. if (pi.skipOnPointerObservable) {
  22898. return;
  22899. }
  22900. }
  22901. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22902. return;
  22903. }
  22904. _this._startingPointerPosition.x = _this._pointerX;
  22905. _this._startingPointerPosition.y = _this._pointerY;
  22906. _this._startingPointerTime = new Date().getTime();
  22907. if (!_this.pointerDownPredicate) {
  22908. _this.pointerDownPredicate = function (mesh) {
  22909. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22910. };
  22911. }
  22912. // Meshes
  22913. _this._pickedDownMesh = null;
  22914. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22915. _this._processPointerDown(pickResult, evt);
  22916. // Sprites
  22917. _this._pickedDownSprite = null;
  22918. if (_this.spriteManagers.length > 0) {
  22919. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22920. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22921. if (pickResult.pickedSprite.actionManager) {
  22922. _this._pickedDownSprite = pickResult.pickedSprite;
  22923. switch (evt.button) {
  22924. case 0:
  22925. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22926. break;
  22927. case 1:
  22928. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22929. break;
  22930. case 2:
  22931. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22932. break;
  22933. }
  22934. if (pickResult.pickedSprite.actionManager) {
  22935. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22936. }
  22937. }
  22938. }
  22939. }
  22940. };
  22941. this._onPointerUp = function (evt) {
  22942. if (_this._totalPointersPressed === 0) {
  22943. return; // So we need to test it the pointer down was pressed before.
  22944. }
  22945. _this._totalPointersPressed--;
  22946. _this._pickedUpMesh = null;
  22947. _this._meshPickProceed = false;
  22948. _this._updatePointerPosition(evt);
  22949. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22950. // PreObservable support
  22951. if (_this.onPrePointerObservable.hasObservers()) {
  22952. if (!clickInfo.ignore) {
  22953. if (!clickInfo.hasSwiped) {
  22954. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22955. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22956. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22957. _this.onPrePointerObservable.notifyObservers(pi, type);
  22958. if (pi.skipOnPointerObservable) {
  22959. return;
  22960. }
  22961. }
  22962. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22963. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22964. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22965. _this.onPrePointerObservable.notifyObservers(pi, type);
  22966. if (pi.skipOnPointerObservable) {
  22967. return;
  22968. }
  22969. }
  22970. }
  22971. }
  22972. else {
  22973. var type = BABYLON.PointerEventTypes.POINTERUP;
  22974. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22975. _this.onPrePointerObservable.notifyObservers(pi, type);
  22976. if (pi.skipOnPointerObservable) {
  22977. return;
  22978. }
  22979. }
  22980. }
  22981. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22982. return;
  22983. }
  22984. if (!_this.pointerUpPredicate) {
  22985. _this.pointerUpPredicate = function (mesh) {
  22986. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22987. };
  22988. }
  22989. // Meshes
  22990. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22991. _this._initActionManager(null, clickInfo);
  22992. }
  22993. if (!pickResult) {
  22994. pickResult = _this._currentPickResult;
  22995. }
  22996. _this._processPointerUp(pickResult, evt, clickInfo);
  22997. // Sprites
  22998. if (_this.spriteManagers.length > 0) {
  22999. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23000. if (spritePickResult) {
  23001. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23002. if (spritePickResult.pickedSprite.actionManager) {
  23003. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23004. if (spritePickResult.pickedSprite.actionManager) {
  23005. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23006. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23007. }
  23008. }
  23009. }
  23010. }
  23011. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23012. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23013. }
  23014. }
  23015. }
  23016. _this._previousPickResult = _this._currentPickResult;
  23017. });
  23018. };
  23019. this._onKeyDown = function (evt) {
  23020. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23021. if (_this.onPreKeyboardObservable.hasObservers()) {
  23022. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23023. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23024. if (pi.skipOnPointerObservable) {
  23025. return;
  23026. }
  23027. }
  23028. if (_this.onKeyboardObservable.hasObservers()) {
  23029. var pi = new BABYLON.KeyboardInfo(type, evt);
  23030. _this.onKeyboardObservable.notifyObservers(pi, type);
  23031. }
  23032. if (_this.actionManager) {
  23033. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23034. }
  23035. };
  23036. this._onKeyUp = function (evt) {
  23037. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23038. if (_this.onPreKeyboardObservable.hasObservers()) {
  23039. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23040. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23041. if (pi.skipOnPointerObservable) {
  23042. return;
  23043. }
  23044. }
  23045. if (_this.onKeyboardObservable.hasObservers()) {
  23046. var pi = new BABYLON.KeyboardInfo(type, evt);
  23047. _this.onKeyboardObservable.notifyObservers(pi, type);
  23048. }
  23049. if (_this.actionManager) {
  23050. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23051. }
  23052. };
  23053. var engine = this.getEngine();
  23054. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23055. if (!canvas) {
  23056. return;
  23057. }
  23058. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23059. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23060. });
  23061. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23062. if (!canvas) {
  23063. return;
  23064. }
  23065. canvas.removeEventListener("keydown", _this._onKeyDown);
  23066. canvas.removeEventListener("keyup", _this._onKeyUp);
  23067. });
  23068. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23069. var canvas = this._engine.getRenderingCanvas();
  23070. if (!canvas) {
  23071. return;
  23072. }
  23073. if (attachMove) {
  23074. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23075. // Wheel
  23076. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23077. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23078. }
  23079. if (attachDown) {
  23080. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23081. }
  23082. if (attachUp) {
  23083. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23084. }
  23085. canvas.tabIndex = 1;
  23086. };
  23087. Scene.prototype.detachControl = function () {
  23088. var engine = this.getEngine();
  23089. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23090. var canvas = engine.getRenderingCanvas();
  23091. if (!canvas) {
  23092. return;
  23093. }
  23094. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23095. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23096. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23097. if (this._onCanvasBlurObserver) {
  23098. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23099. }
  23100. if (this._onCanvasFocusObserver) {
  23101. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23102. }
  23103. // Wheel
  23104. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23105. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23106. // Keyboard
  23107. canvas.removeEventListener("keydown", this._onKeyDown);
  23108. canvas.removeEventListener("keyup", this._onKeyUp);
  23109. // Observables
  23110. this.onKeyboardObservable.clear();
  23111. this.onPreKeyboardObservable.clear();
  23112. this.onPointerObservable.clear();
  23113. this.onPrePointerObservable.clear();
  23114. };
  23115. /**
  23116. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23117. * Delay loaded resources are not taking in account
  23118. * @return true if all required resources are ready
  23119. */
  23120. Scene.prototype.isReady = function () {
  23121. if (this._isDisposed) {
  23122. return false;
  23123. }
  23124. if (this._pendingData.length > 0) {
  23125. return false;
  23126. }
  23127. var index;
  23128. var engine = this.getEngine();
  23129. // Geometries
  23130. for (index = 0; index < this._geometries.length; index++) {
  23131. var geometry = this._geometries[index];
  23132. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23133. return false;
  23134. }
  23135. }
  23136. // Meshes
  23137. for (index = 0; index < this.meshes.length; index++) {
  23138. var mesh = this.meshes[index];
  23139. if (!mesh.isEnabled()) {
  23140. continue;
  23141. }
  23142. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23143. continue;
  23144. }
  23145. if (!mesh.isReady(true)) {
  23146. return false;
  23147. }
  23148. // Effect layers
  23149. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23150. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23151. var layer = _a[_i];
  23152. if (!layer.hasMesh(mesh)) {
  23153. continue;
  23154. }
  23155. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23156. var subMesh = _c[_b];
  23157. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23158. return false;
  23159. }
  23160. }
  23161. }
  23162. }
  23163. // Particles
  23164. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  23165. var particleSystem = _e[_d];
  23166. if (!particleSystem.isReady()) {
  23167. return false;
  23168. }
  23169. }
  23170. return true;
  23171. };
  23172. Scene.prototype.resetCachedMaterial = function () {
  23173. this._cachedMaterial = null;
  23174. this._cachedEffect = null;
  23175. this._cachedVisibility = null;
  23176. };
  23177. Scene.prototype.registerBeforeRender = function (func) {
  23178. this.onBeforeRenderObservable.add(func);
  23179. };
  23180. Scene.prototype.unregisterBeforeRender = function (func) {
  23181. this.onBeforeRenderObservable.removeCallback(func);
  23182. };
  23183. Scene.prototype.registerAfterRender = function (func) {
  23184. this.onAfterRenderObservable.add(func);
  23185. };
  23186. Scene.prototype.unregisterAfterRender = function (func) {
  23187. this.onAfterRenderObservable.removeCallback(func);
  23188. };
  23189. Scene.prototype._executeOnceBeforeRender = function (func) {
  23190. var _this = this;
  23191. var execFunc = function () {
  23192. func();
  23193. setTimeout(function () {
  23194. _this.unregisterBeforeRender(execFunc);
  23195. });
  23196. };
  23197. this.registerBeforeRender(execFunc);
  23198. };
  23199. /**
  23200. * The provided function will run before render once and will be disposed afterwards.
  23201. * A timeout delay can be provided so that the function will be executed in N ms.
  23202. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23203. * @param func The function to be executed.
  23204. * @param timeout optional delay in ms
  23205. */
  23206. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23207. var _this = this;
  23208. if (timeout !== undefined) {
  23209. setTimeout(function () {
  23210. _this._executeOnceBeforeRender(func);
  23211. }, timeout);
  23212. }
  23213. else {
  23214. this._executeOnceBeforeRender(func);
  23215. }
  23216. };
  23217. Scene.prototype._addPendingData = function (data) {
  23218. this._pendingData.push(data);
  23219. };
  23220. Scene.prototype._removePendingData = function (data) {
  23221. var wasLoading = this.isLoading;
  23222. var index = this._pendingData.indexOf(data);
  23223. if (index !== -1) {
  23224. this._pendingData.splice(index, 1);
  23225. }
  23226. if (wasLoading && !this.isLoading) {
  23227. this.onDataLoadedObservable.notifyObservers(this);
  23228. }
  23229. };
  23230. Scene.prototype.getWaitingItemsCount = function () {
  23231. return this._pendingData.length;
  23232. };
  23233. Object.defineProperty(Scene.prototype, "isLoading", {
  23234. get: function () {
  23235. return this._pendingData.length > 0;
  23236. },
  23237. enumerable: true,
  23238. configurable: true
  23239. });
  23240. /**
  23241. * Registers a function to be executed when the scene is ready.
  23242. * @param {Function} func - the function to be executed.
  23243. */
  23244. Scene.prototype.executeWhenReady = function (func) {
  23245. var _this = this;
  23246. this.onReadyObservable.add(func);
  23247. if (this._executeWhenReadyTimeoutId !== -1) {
  23248. return;
  23249. }
  23250. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23251. _this._checkIsReady();
  23252. }, 150);
  23253. };
  23254. /**
  23255. * Returns a promise that resolves when the scene is ready.
  23256. * @returns A promise that resolves when the scene is ready.
  23257. */
  23258. Scene.prototype.whenReadyAsync = function () {
  23259. var _this = this;
  23260. return new Promise(function (resolve) {
  23261. _this.executeWhenReady(function () {
  23262. resolve();
  23263. });
  23264. });
  23265. };
  23266. Scene.prototype._checkIsReady = function () {
  23267. var _this = this;
  23268. if (this.isReady()) {
  23269. this.onReadyObservable.notifyObservers(this);
  23270. this.onReadyObservable.clear();
  23271. this._executeWhenReadyTimeoutId = -1;
  23272. return;
  23273. }
  23274. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23275. _this._checkIsReady();
  23276. }, 150);
  23277. };
  23278. // Animations
  23279. /**
  23280. * Will start the animation sequence of a given target
  23281. * @param target defines the target
  23282. * @param from defines from which frame should animation start
  23283. * @param to defines until which frame should animation run.
  23284. * @param weight defines the weight to apply to the animation (1.0 by default)
  23285. * @param loop defines if the animation loops
  23286. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23287. * @param onAnimationEnd defines the function to be executed when the animation ends
  23288. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23289. * @returns the animatable object created for this animation
  23290. * @see BABYLON.Animatable
  23291. */
  23292. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23293. if (weight === void 0) { weight = 1.0; }
  23294. if (speedRatio === void 0) { speedRatio = 1.0; }
  23295. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23296. returnedAnimatable.weight = weight;
  23297. return returnedAnimatable;
  23298. };
  23299. /**
  23300. * Will start the animation sequence of a given target
  23301. * @param target defines the target
  23302. * @param from defines from which frame should animation start
  23303. * @param to defines until which frame should animation run.
  23304. * @param loop defines if the animation loops
  23305. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23306. * @param onAnimationEnd defines the function to be executed when the animation ends
  23307. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23308. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23309. * @returns the animatable object created for this animation
  23310. * @see BABYLON.Animatable
  23311. */
  23312. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23313. if (speedRatio === void 0) { speedRatio = 1.0; }
  23314. if (stopCurrent === void 0) { stopCurrent = true; }
  23315. if (from > to && speedRatio > 0) {
  23316. speedRatio *= -1;
  23317. }
  23318. if (stopCurrent) {
  23319. this.stopAnimation(target);
  23320. }
  23321. if (!animatable) {
  23322. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23323. }
  23324. // Local animations
  23325. if (target.animations) {
  23326. animatable.appendAnimations(target, target.animations);
  23327. }
  23328. // Children animations
  23329. if (target.getAnimatables) {
  23330. var animatables = target.getAnimatables();
  23331. for (var index = 0; index < animatables.length; index++) {
  23332. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23333. }
  23334. }
  23335. animatable.reset();
  23336. return animatable;
  23337. };
  23338. /**
  23339. * Begin a new animation on a given node
  23340. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23341. * @param {BABYLON.Animation[]} defines the list of animations to start
  23342. * @param {number} from defines the initial value
  23343. * @param {number} to defines the final value
  23344. * @param {boolean} loop defines if you want animation to loop (off by default)
  23345. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23346. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23347. * @returns the list of created animatables
  23348. */
  23349. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23350. if (speedRatio === undefined) {
  23351. speedRatio = 1.0;
  23352. }
  23353. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23354. return animatable;
  23355. };
  23356. /**
  23357. * Begin a new animation on a given node and its hierarchy
  23358. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23359. * @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.
  23360. * @param {BABYLON.Animation[]} defines the list of animations to start
  23361. * @param {number} from defines the initial value
  23362. * @param {number} to defines the final value
  23363. * @param {boolean} loop defines if you want animation to loop (off by default)
  23364. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23365. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23366. * @returns the list of animatables created for all nodes
  23367. */
  23368. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23369. var children = target.getDescendants(directDescendantsOnly);
  23370. var result = [];
  23371. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23372. var child = children_1[_i];
  23373. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23374. }
  23375. return result;
  23376. };
  23377. Scene.prototype.getAnimatableByTarget = function (target) {
  23378. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23379. if (this._activeAnimatables[index].target === target) {
  23380. return this._activeAnimatables[index];
  23381. }
  23382. }
  23383. return null;
  23384. };
  23385. /**
  23386. * Gets all animatables associated with a given target
  23387. * @param target defines the target to look animatables for
  23388. * @returns an array of Animatables
  23389. */
  23390. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23391. var result = [];
  23392. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23393. if (this._activeAnimatables[index].target === target) {
  23394. result.push(this._activeAnimatables[index]);
  23395. }
  23396. }
  23397. return result;
  23398. };
  23399. Object.defineProperty(Scene.prototype, "animatables", {
  23400. get: function () {
  23401. return this._activeAnimatables;
  23402. },
  23403. enumerable: true,
  23404. configurable: true
  23405. });
  23406. /**
  23407. * Will stop the animation of the given target
  23408. * @param target - the target
  23409. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23410. * @see beginAnimation
  23411. */
  23412. Scene.prototype.stopAnimation = function (target, animationName) {
  23413. var animatables = this.getAllAnimatablesByTarget(target);
  23414. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23415. var animatable = animatables_1[_i];
  23416. animatable.stop(animationName);
  23417. }
  23418. };
  23419. /**
  23420. * Stops and removes all animations that have been applied to the scene
  23421. */
  23422. Scene.prototype.stopAllAnimations = function () {
  23423. if (this._activeAnimatables) {
  23424. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23425. this._activeAnimatables[i].stop();
  23426. }
  23427. this._activeAnimatables = [];
  23428. }
  23429. };
  23430. Scene.prototype._animate = function () {
  23431. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23432. return;
  23433. }
  23434. // Getting time
  23435. var now = BABYLON.Tools.Now;
  23436. if (!this._animationTimeLast) {
  23437. if (this._pendingData.length > 0) {
  23438. return;
  23439. }
  23440. this._animationTimeLast = now;
  23441. }
  23442. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23443. this._animationTime += deltaTime;
  23444. this._animationTimeLast = now;
  23445. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23446. this._activeAnimatables[index]._animate(this._animationTime);
  23447. }
  23448. // Late animation bindings
  23449. this._processLateAnimationBindings();
  23450. };
  23451. /** @ignore */
  23452. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23453. var target = runtimeAnimation.target;
  23454. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23455. if (!target._lateAnimationHolders) {
  23456. target._lateAnimationHolders = {};
  23457. }
  23458. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23459. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23460. totalWeight: 0,
  23461. animations: []
  23462. };
  23463. }
  23464. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23465. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23466. };
  23467. Scene.prototype._processLateAnimationBindings = function () {
  23468. if (!this._registeredForLateAnimationBindings.length) {
  23469. return;
  23470. }
  23471. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23472. var target = this._registeredForLateAnimationBindings.data[index];
  23473. for (var path in target._lateAnimationHolders) {
  23474. var holder = target._lateAnimationHolders[path];
  23475. // Sanity check
  23476. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23477. continue;
  23478. }
  23479. var normalizer = 1.0;
  23480. var finalValue = void 0;
  23481. if (holder.totalWeight < 1.0) {
  23482. // We need to mix the original value in
  23483. var originalValue = holder.animations[0].originalValue;
  23484. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23485. }
  23486. else {
  23487. // We need to normalize the weights
  23488. normalizer = holder.totalWeight;
  23489. }
  23490. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23491. var runtimeAnimation = holder.animations[animIndex];
  23492. if (finalValue) {
  23493. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23494. }
  23495. else {
  23496. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23497. }
  23498. }
  23499. runtimeAnimation.target[path] = finalValue;
  23500. }
  23501. target._lateAnimationHolders = {};
  23502. }
  23503. this._registeredForLateAnimationBindings.reset();
  23504. };
  23505. // Matrix
  23506. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23507. this._useAlternateCameraConfiguration = active;
  23508. };
  23509. Scene.prototype.getViewMatrix = function () {
  23510. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23511. };
  23512. Scene.prototype.getProjectionMatrix = function () {
  23513. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23514. };
  23515. Scene.prototype.getTransformMatrix = function () {
  23516. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23517. };
  23518. Scene.prototype.setTransformMatrix = function (view, projection) {
  23519. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23520. return;
  23521. }
  23522. this._viewUpdateFlag = view.updateFlag;
  23523. this._projectionUpdateFlag = projection.updateFlag;
  23524. this._viewMatrix = view;
  23525. this._projectionMatrix = projection;
  23526. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23527. // Update frustum
  23528. if (!this._frustumPlanes) {
  23529. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23530. }
  23531. else {
  23532. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23533. }
  23534. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23535. var otherCamera = this.activeCamera._alternateCamera;
  23536. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23537. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23538. }
  23539. if (this._sceneUbo.useUbo) {
  23540. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23541. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23542. this._sceneUbo.update();
  23543. }
  23544. };
  23545. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23546. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23547. return;
  23548. }
  23549. this._alternateViewUpdateFlag = view.updateFlag;
  23550. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23551. this._alternateViewMatrix = view;
  23552. this._alternateProjectionMatrix = projection;
  23553. if (!this._alternateTransformMatrix) {
  23554. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23555. }
  23556. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23557. if (!this._alternateSceneUbo) {
  23558. this._createAlternateUbo();
  23559. }
  23560. if (this._alternateSceneUbo.useUbo) {
  23561. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23562. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23563. this._alternateSceneUbo.update();
  23564. }
  23565. };
  23566. Scene.prototype.getSceneUniformBuffer = function () {
  23567. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23568. };
  23569. // Methods
  23570. Scene.prototype.getUniqueId = function () {
  23571. var result = Scene._uniqueIdCounter;
  23572. Scene._uniqueIdCounter++;
  23573. return result;
  23574. };
  23575. Scene.prototype.addMesh = function (newMesh) {
  23576. this.meshes.push(newMesh);
  23577. //notify the collision coordinator
  23578. if (this.collisionCoordinator) {
  23579. this.collisionCoordinator.onMeshAdded(newMesh);
  23580. }
  23581. newMesh._resyncLightSources();
  23582. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23583. };
  23584. Scene.prototype.removeMesh = function (toRemove) {
  23585. var index = this.meshes.indexOf(toRemove);
  23586. if (index !== -1) {
  23587. // Remove from the scene if mesh found
  23588. this.meshes.splice(index, 1);
  23589. }
  23590. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23591. return index;
  23592. };
  23593. Scene.prototype.addTransformNode = function (newTransformNode) {
  23594. this.transformNodes.push(newTransformNode);
  23595. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23596. };
  23597. Scene.prototype.removeTransformNode = function (toRemove) {
  23598. var index = this.transformNodes.indexOf(toRemove);
  23599. if (index !== -1) {
  23600. // Remove from the scene if found
  23601. this.transformNodes.splice(index, 1);
  23602. }
  23603. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23604. return index;
  23605. };
  23606. Scene.prototype.removeSkeleton = function (toRemove) {
  23607. var index = this.skeletons.indexOf(toRemove);
  23608. if (index !== -1) {
  23609. // Remove from the scene if found
  23610. this.skeletons.splice(index, 1);
  23611. }
  23612. return index;
  23613. };
  23614. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23615. var index = this.morphTargetManagers.indexOf(toRemove);
  23616. if (index !== -1) {
  23617. // Remove from the scene if found
  23618. this.morphTargetManagers.splice(index, 1);
  23619. }
  23620. return index;
  23621. };
  23622. Scene.prototype.removeLight = function (toRemove) {
  23623. var index = this.lights.indexOf(toRemove);
  23624. if (index !== -1) {
  23625. // Remove from meshes
  23626. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23627. var mesh = _a[_i];
  23628. mesh._removeLightSource(toRemove);
  23629. }
  23630. // Remove from the scene if mesh found
  23631. this.lights.splice(index, 1);
  23632. this.sortLightsByPriority();
  23633. }
  23634. this.onLightRemovedObservable.notifyObservers(toRemove);
  23635. return index;
  23636. };
  23637. Scene.prototype.removeCamera = function (toRemove) {
  23638. var index = this.cameras.indexOf(toRemove);
  23639. if (index !== -1) {
  23640. // Remove from the scene if mesh found
  23641. this.cameras.splice(index, 1);
  23642. }
  23643. // Remove from activeCameras
  23644. var index2 = this.activeCameras.indexOf(toRemove);
  23645. if (index2 !== -1) {
  23646. // Remove from the scene if mesh found
  23647. this.activeCameras.splice(index2, 1);
  23648. }
  23649. // Reset the activeCamera
  23650. if (this.activeCamera === toRemove) {
  23651. if (this.cameras.length > 0) {
  23652. this.activeCamera = this.cameras[0];
  23653. }
  23654. else {
  23655. this.activeCamera = null;
  23656. }
  23657. }
  23658. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23659. return index;
  23660. };
  23661. Scene.prototype.removeParticleSystem = function (toRemove) {
  23662. var index = this.particleSystems.indexOf(toRemove);
  23663. if (index !== -1) {
  23664. this.particleSystems.splice(index, 1);
  23665. }
  23666. return index;
  23667. };
  23668. ;
  23669. Scene.prototype.removeAnimation = function (toRemove) {
  23670. var index = this.animations.indexOf(toRemove);
  23671. if (index !== -1) {
  23672. this.animations.splice(index, 1);
  23673. }
  23674. return index;
  23675. };
  23676. ;
  23677. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23678. var index = this.multiMaterials.indexOf(toRemove);
  23679. if (index !== -1) {
  23680. this.multiMaterials.splice(index, 1);
  23681. }
  23682. return index;
  23683. };
  23684. ;
  23685. Scene.prototype.removeMaterial = function (toRemove) {
  23686. var index = this.materials.indexOf(toRemove);
  23687. if (index !== -1) {
  23688. this.materials.splice(index, 1);
  23689. }
  23690. return index;
  23691. };
  23692. ;
  23693. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23694. var index = this.lensFlareSystems.indexOf(toRemove);
  23695. if (index !== -1) {
  23696. this.lensFlareSystems.splice(index, 1);
  23697. }
  23698. return index;
  23699. };
  23700. ;
  23701. Scene.prototype.removeActionManager = function (toRemove) {
  23702. var index = this._actionManagers.indexOf(toRemove);
  23703. if (index !== -1) {
  23704. this._actionManagers.splice(index, 1);
  23705. }
  23706. return index;
  23707. };
  23708. ;
  23709. Scene.prototype.addLight = function (newLight) {
  23710. this.lights.push(newLight);
  23711. this.sortLightsByPriority();
  23712. // Add light to all meshes (To support if the light is removed and then readded)
  23713. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23714. var mesh = _a[_i];
  23715. if (mesh._lightSources.indexOf(newLight) === -1) {
  23716. mesh._lightSources.push(newLight);
  23717. mesh._resyncLightSources();
  23718. }
  23719. }
  23720. this.onNewLightAddedObservable.notifyObservers(newLight);
  23721. };
  23722. Scene.prototype.sortLightsByPriority = function () {
  23723. if (this.requireLightSorting) {
  23724. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23725. }
  23726. };
  23727. Scene.prototype.addCamera = function (newCamera) {
  23728. this.cameras.push(newCamera);
  23729. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23730. };
  23731. Scene.prototype.addSkeleton = function (newSkeleton) {
  23732. this.skeletons.push(newSkeleton);
  23733. };
  23734. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23735. this.particleSystems.push(newParticleSystem);
  23736. };
  23737. Scene.prototype.addAnimation = function (newAnimation) {
  23738. this.animations.push(newAnimation);
  23739. };
  23740. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23741. this.multiMaterials.push(newMultiMaterial);
  23742. };
  23743. Scene.prototype.addMaterial = function (newMaterial) {
  23744. this.materials.push(newMaterial);
  23745. };
  23746. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23747. this.morphTargetManagers.push(newMorphTargetManager);
  23748. };
  23749. Scene.prototype.addGeometry = function (newGeometrie) {
  23750. this._geometries.push(newGeometrie);
  23751. };
  23752. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23753. this.lensFlareSystems.push(newLensFlareSystem);
  23754. };
  23755. Scene.prototype.addActionManager = function (newActionManager) {
  23756. this._actionManagers.push(newActionManager);
  23757. };
  23758. /**
  23759. * Switch active camera
  23760. * @param {Camera} newCamera - new active camera
  23761. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23762. */
  23763. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23764. if (attachControl === void 0) { attachControl = true; }
  23765. var canvas = this._engine.getRenderingCanvas();
  23766. if (!canvas) {
  23767. return;
  23768. }
  23769. if (this.activeCamera) {
  23770. this.activeCamera.detachControl(canvas);
  23771. }
  23772. this.activeCamera = newCamera;
  23773. if (attachControl) {
  23774. newCamera.attachControl(canvas);
  23775. }
  23776. };
  23777. /**
  23778. * sets the active camera of the scene using its ID
  23779. * @param {string} id - the camera's ID
  23780. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23781. * @see activeCamera
  23782. */
  23783. Scene.prototype.setActiveCameraByID = function (id) {
  23784. var camera = this.getCameraByID(id);
  23785. if (camera) {
  23786. this.activeCamera = camera;
  23787. return camera;
  23788. }
  23789. return null;
  23790. };
  23791. /**
  23792. * sets the active camera of the scene using its name
  23793. * @param {string} name - the camera's name
  23794. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23795. * @see activeCamera
  23796. */
  23797. Scene.prototype.setActiveCameraByName = function (name) {
  23798. var camera = this.getCameraByName(name);
  23799. if (camera) {
  23800. this.activeCamera = camera;
  23801. return camera;
  23802. }
  23803. return null;
  23804. };
  23805. /**
  23806. * get an animation group using its name
  23807. * @param {string} the material's name
  23808. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23809. */
  23810. Scene.prototype.getAnimationGroupByName = function (name) {
  23811. for (var index = 0; index < this.animationGroups.length; index++) {
  23812. if (this.animationGroups[index].name === name) {
  23813. return this.animationGroups[index];
  23814. }
  23815. }
  23816. return null;
  23817. };
  23818. /**
  23819. * get a material using its id
  23820. * @param {string} the material's ID
  23821. * @return {BABYLON.Material|null} the material or null if none found.
  23822. */
  23823. Scene.prototype.getMaterialByID = function (id) {
  23824. for (var index = 0; index < this.materials.length; index++) {
  23825. if (this.materials[index].id === id) {
  23826. return this.materials[index];
  23827. }
  23828. }
  23829. return null;
  23830. };
  23831. /**
  23832. * get a material using its name
  23833. * @param {string} the material's name
  23834. * @return {BABYLON.Material|null} the material or null if none found.
  23835. */
  23836. Scene.prototype.getMaterialByName = function (name) {
  23837. for (var index = 0; index < this.materials.length; index++) {
  23838. if (this.materials[index].name === name) {
  23839. return this.materials[index];
  23840. }
  23841. }
  23842. return null;
  23843. };
  23844. Scene.prototype.getLensFlareSystemByName = function (name) {
  23845. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23846. if (this.lensFlareSystems[index].name === name) {
  23847. return this.lensFlareSystems[index];
  23848. }
  23849. }
  23850. return null;
  23851. };
  23852. Scene.prototype.getLensFlareSystemByID = function (id) {
  23853. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23854. if (this.lensFlareSystems[index].id === id) {
  23855. return this.lensFlareSystems[index];
  23856. }
  23857. }
  23858. return null;
  23859. };
  23860. Scene.prototype.getCameraByID = function (id) {
  23861. for (var index = 0; index < this.cameras.length; index++) {
  23862. if (this.cameras[index].id === id) {
  23863. return this.cameras[index];
  23864. }
  23865. }
  23866. return null;
  23867. };
  23868. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23869. for (var index = 0; index < this.cameras.length; index++) {
  23870. if (this.cameras[index].uniqueId === uniqueId) {
  23871. return this.cameras[index];
  23872. }
  23873. }
  23874. return null;
  23875. };
  23876. /**
  23877. * get a camera using its name
  23878. * @param {string} the camera's name
  23879. * @return {BABYLON.Camera|null} the camera or null if none found.
  23880. */
  23881. Scene.prototype.getCameraByName = function (name) {
  23882. for (var index = 0; index < this.cameras.length; index++) {
  23883. if (this.cameras[index].name === name) {
  23884. return this.cameras[index];
  23885. }
  23886. }
  23887. return null;
  23888. };
  23889. /**
  23890. * get a bone using its id
  23891. * @param {string} the bone's id
  23892. * @return {BABYLON.Bone|null} the bone or null if not found
  23893. */
  23894. Scene.prototype.getBoneByID = function (id) {
  23895. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23896. var skeleton = this.skeletons[skeletonIndex];
  23897. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23898. if (skeleton.bones[boneIndex].id === id) {
  23899. return skeleton.bones[boneIndex];
  23900. }
  23901. }
  23902. }
  23903. return null;
  23904. };
  23905. /**
  23906. * get a bone using its id
  23907. * @param {string} the bone's name
  23908. * @return {BABYLON.Bone|null} the bone or null if not found
  23909. */
  23910. Scene.prototype.getBoneByName = function (name) {
  23911. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23912. var skeleton = this.skeletons[skeletonIndex];
  23913. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23914. if (skeleton.bones[boneIndex].name === name) {
  23915. return skeleton.bones[boneIndex];
  23916. }
  23917. }
  23918. }
  23919. return null;
  23920. };
  23921. /**
  23922. * get a light node using its name
  23923. * @param {string} the light's name
  23924. * @return {BABYLON.Light|null} the light or null if none found.
  23925. */
  23926. Scene.prototype.getLightByName = function (name) {
  23927. for (var index = 0; index < this.lights.length; index++) {
  23928. if (this.lights[index].name === name) {
  23929. return this.lights[index];
  23930. }
  23931. }
  23932. return null;
  23933. };
  23934. /**
  23935. * get a light node using its ID
  23936. * @param {string} the light's id
  23937. * @return {BABYLON.Light|null} the light or null if none found.
  23938. */
  23939. Scene.prototype.getLightByID = function (id) {
  23940. for (var index = 0; index < this.lights.length; index++) {
  23941. if (this.lights[index].id === id) {
  23942. return this.lights[index];
  23943. }
  23944. }
  23945. return null;
  23946. };
  23947. /**
  23948. * get a light node using its scene-generated unique ID
  23949. * @param {number} the light's unique id
  23950. * @return {BABYLON.Light|null} the light or null if none found.
  23951. */
  23952. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23953. for (var index = 0; index < this.lights.length; index++) {
  23954. if (this.lights[index].uniqueId === uniqueId) {
  23955. return this.lights[index];
  23956. }
  23957. }
  23958. return null;
  23959. };
  23960. /**
  23961. * get a particle system by id
  23962. * @param id {number} the particle system id
  23963. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23964. */
  23965. Scene.prototype.getParticleSystemByID = function (id) {
  23966. for (var index = 0; index < this.particleSystems.length; index++) {
  23967. if (this.particleSystems[index].id === id) {
  23968. return this.particleSystems[index];
  23969. }
  23970. }
  23971. return null;
  23972. };
  23973. /**
  23974. * get a geometry using its ID
  23975. * @param {string} the geometry's id
  23976. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23977. */
  23978. Scene.prototype.getGeometryByID = function (id) {
  23979. for (var index = 0; index < this._geometries.length; index++) {
  23980. if (this._geometries[index].id === id) {
  23981. return this._geometries[index];
  23982. }
  23983. }
  23984. return null;
  23985. };
  23986. /**
  23987. * add a new geometry to this scene.
  23988. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23989. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23990. * @return {boolean} was the geometry added or not
  23991. */
  23992. Scene.prototype.pushGeometry = function (geometry, force) {
  23993. if (!force && this.getGeometryByID(geometry.id)) {
  23994. return false;
  23995. }
  23996. this._geometries.push(geometry);
  23997. //notify the collision coordinator
  23998. if (this.collisionCoordinator) {
  23999. this.collisionCoordinator.onGeometryAdded(geometry);
  24000. }
  24001. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24002. return true;
  24003. };
  24004. /**
  24005. * Removes an existing geometry
  24006. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24007. * @return {boolean} was the geometry removed or not
  24008. */
  24009. Scene.prototype.removeGeometry = function (geometry) {
  24010. var index = this._geometries.indexOf(geometry);
  24011. if (index > -1) {
  24012. this._geometries.splice(index, 1);
  24013. //notify the collision coordinator
  24014. if (this.collisionCoordinator) {
  24015. this.collisionCoordinator.onGeometryDeleted(geometry);
  24016. }
  24017. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24018. return true;
  24019. }
  24020. return false;
  24021. };
  24022. Scene.prototype.getGeometries = function () {
  24023. return this._geometries;
  24024. };
  24025. /**
  24026. * Get the first added mesh found of a given ID
  24027. * @param {string} id - the id to search for
  24028. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24029. */
  24030. Scene.prototype.getMeshByID = function (id) {
  24031. for (var index = 0; index < this.meshes.length; index++) {
  24032. if (this.meshes[index].id === id) {
  24033. return this.meshes[index];
  24034. }
  24035. }
  24036. return null;
  24037. };
  24038. Scene.prototype.getMeshesByID = function (id) {
  24039. return this.meshes.filter(function (m) {
  24040. return m.id === id;
  24041. });
  24042. };
  24043. /**
  24044. * Get the first added transform node found of a given ID
  24045. * @param {string} id - the id to search for
  24046. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24047. */
  24048. Scene.prototype.getTransformNodeByID = function (id) {
  24049. for (var index = 0; index < this.transformNodes.length; index++) {
  24050. if (this.transformNodes[index].id === id) {
  24051. return this.transformNodes[index];
  24052. }
  24053. }
  24054. return null;
  24055. };
  24056. Scene.prototype.getTransformNodesByID = function (id) {
  24057. return this.transformNodes.filter(function (m) {
  24058. return m.id === id;
  24059. });
  24060. };
  24061. /**
  24062. * Get a mesh with its auto-generated unique id
  24063. * @param {number} uniqueId - the unique id to search for
  24064. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24065. */
  24066. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24067. for (var index = 0; index < this.meshes.length; index++) {
  24068. if (this.meshes[index].uniqueId === uniqueId) {
  24069. return this.meshes[index];
  24070. }
  24071. }
  24072. return null;
  24073. };
  24074. /**
  24075. * Get a the last added mesh found of a given ID
  24076. * @param {string} id - the id to search for
  24077. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24078. */
  24079. Scene.prototype.getLastMeshByID = function (id) {
  24080. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24081. if (this.meshes[index].id === id) {
  24082. return this.meshes[index];
  24083. }
  24084. }
  24085. return null;
  24086. };
  24087. /**
  24088. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24089. * @param {string} id - the id to search for
  24090. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24091. */
  24092. Scene.prototype.getLastEntryByID = function (id) {
  24093. var index;
  24094. for (index = this.meshes.length - 1; index >= 0; index--) {
  24095. if (this.meshes[index].id === id) {
  24096. return this.meshes[index];
  24097. }
  24098. }
  24099. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24100. if (this.transformNodes[index].id === id) {
  24101. return this.transformNodes[index];
  24102. }
  24103. }
  24104. for (index = this.cameras.length - 1; index >= 0; index--) {
  24105. if (this.cameras[index].id === id) {
  24106. return this.cameras[index];
  24107. }
  24108. }
  24109. for (index = this.lights.length - 1; index >= 0; index--) {
  24110. if (this.lights[index].id === id) {
  24111. return this.lights[index];
  24112. }
  24113. }
  24114. return null;
  24115. };
  24116. Scene.prototype.getNodeByID = function (id) {
  24117. var mesh = this.getMeshByID(id);
  24118. if (mesh) {
  24119. return mesh;
  24120. }
  24121. var light = this.getLightByID(id);
  24122. if (light) {
  24123. return light;
  24124. }
  24125. var camera = this.getCameraByID(id);
  24126. if (camera) {
  24127. return camera;
  24128. }
  24129. var bone = this.getBoneByID(id);
  24130. return bone;
  24131. };
  24132. Scene.prototype.getNodeByName = function (name) {
  24133. var mesh = this.getMeshByName(name);
  24134. if (mesh) {
  24135. return mesh;
  24136. }
  24137. var light = this.getLightByName(name);
  24138. if (light) {
  24139. return light;
  24140. }
  24141. var camera = this.getCameraByName(name);
  24142. if (camera) {
  24143. return camera;
  24144. }
  24145. var bone = this.getBoneByName(name);
  24146. return bone;
  24147. };
  24148. Scene.prototype.getMeshByName = function (name) {
  24149. for (var index = 0; index < this.meshes.length; index++) {
  24150. if (this.meshes[index].name === name) {
  24151. return this.meshes[index];
  24152. }
  24153. }
  24154. return null;
  24155. };
  24156. Scene.prototype.getTransformNodeByName = function (name) {
  24157. for (var index = 0; index < this.transformNodes.length; index++) {
  24158. if (this.transformNodes[index].name === name) {
  24159. return this.transformNodes[index];
  24160. }
  24161. }
  24162. return null;
  24163. };
  24164. Scene.prototype.getSoundByName = function (name) {
  24165. var index;
  24166. if (BABYLON.AudioEngine) {
  24167. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24168. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24169. return this.mainSoundTrack.soundCollection[index];
  24170. }
  24171. }
  24172. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24173. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24174. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24175. return this.soundTracks[sdIndex].soundCollection[index];
  24176. }
  24177. }
  24178. }
  24179. }
  24180. return null;
  24181. };
  24182. Scene.prototype.getLastSkeletonByID = function (id) {
  24183. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24184. if (this.skeletons[index].id === id) {
  24185. return this.skeletons[index];
  24186. }
  24187. }
  24188. return null;
  24189. };
  24190. Scene.prototype.getSkeletonById = function (id) {
  24191. for (var index = 0; index < this.skeletons.length; index++) {
  24192. if (this.skeletons[index].id === id) {
  24193. return this.skeletons[index];
  24194. }
  24195. }
  24196. return null;
  24197. };
  24198. Scene.prototype.getSkeletonByName = function (name) {
  24199. for (var index = 0; index < this.skeletons.length; index++) {
  24200. if (this.skeletons[index].name === name) {
  24201. return this.skeletons[index];
  24202. }
  24203. }
  24204. return null;
  24205. };
  24206. Scene.prototype.getMorphTargetManagerById = function (id) {
  24207. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24208. if (this.morphTargetManagers[index].uniqueId === id) {
  24209. return this.morphTargetManagers[index];
  24210. }
  24211. }
  24212. return null;
  24213. };
  24214. Scene.prototype.isActiveMesh = function (mesh) {
  24215. return (this._activeMeshes.indexOf(mesh) !== -1);
  24216. };
  24217. /**
  24218. * Return a the first highlight layer of the scene with a given name.
  24219. * @param name The name of the highlight layer to look for.
  24220. * @return The highlight layer if found otherwise null.
  24221. */
  24222. Scene.prototype.getHighlightLayerByName = function (name) {
  24223. for (var index = 0; index < this.effectLayers.length; index++) {
  24224. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24225. return this.effectLayers[index];
  24226. }
  24227. }
  24228. return null;
  24229. };
  24230. /**
  24231. * Return a the first highlight layer of the scene with a given name.
  24232. * @param name The name of the highlight layer to look for.
  24233. * @return The highlight layer if found otherwise null.
  24234. */
  24235. Scene.prototype.getGlowLayerByName = function (name) {
  24236. for (var index = 0; index < this.effectLayers.length; index++) {
  24237. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24238. return this.effectLayers[index];
  24239. }
  24240. }
  24241. return null;
  24242. };
  24243. Object.defineProperty(Scene.prototype, "uid", {
  24244. /**
  24245. * Return a unique id as a string which can serve as an identifier for the scene
  24246. */
  24247. get: function () {
  24248. if (!this._uid) {
  24249. this._uid = BABYLON.Tools.RandomId();
  24250. }
  24251. return this._uid;
  24252. },
  24253. enumerable: true,
  24254. configurable: true
  24255. });
  24256. /**
  24257. * Add an externaly attached data from its key.
  24258. * This method call will fail and return false, if such key already exists.
  24259. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24260. * @param key the unique key that identifies the data
  24261. * @param data the data object to associate to the key for this Engine instance
  24262. * @return true if no such key were already present and the data was added successfully, false otherwise
  24263. */
  24264. Scene.prototype.addExternalData = function (key, data) {
  24265. if (!this._externalData) {
  24266. this._externalData = new BABYLON.StringDictionary();
  24267. }
  24268. return this._externalData.add(key, data);
  24269. };
  24270. /**
  24271. * Get an externaly attached data from its key
  24272. * @param key the unique key that identifies the data
  24273. * @return the associated data, if present (can be null), or undefined if not present
  24274. */
  24275. Scene.prototype.getExternalData = function (key) {
  24276. if (!this._externalData) {
  24277. return null;
  24278. }
  24279. return this._externalData.get(key);
  24280. };
  24281. /**
  24282. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24283. * @param key the unique key that identifies the data
  24284. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24285. * @return the associated data, can be null if the factory returned null.
  24286. */
  24287. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24288. if (!this._externalData) {
  24289. this._externalData = new BABYLON.StringDictionary();
  24290. }
  24291. return this._externalData.getOrAddWithFactory(key, factory);
  24292. };
  24293. /**
  24294. * Remove an externaly attached data from the Engine instance
  24295. * @param key the unique key that identifies the data
  24296. * @return true if the data was successfully removed, false if it doesn't exist
  24297. */
  24298. Scene.prototype.removeExternalData = function (key) {
  24299. return this._externalData.remove(key);
  24300. };
  24301. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24302. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24303. if (mesh.showSubMeshesBoundingBox) {
  24304. var boundingInfo = subMesh.getBoundingInfo();
  24305. if (boundingInfo !== null && boundingInfo !== undefined) {
  24306. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24307. }
  24308. }
  24309. var material = subMesh.getMaterial();
  24310. if (material !== null && material !== undefined) {
  24311. // Render targets
  24312. if (material.getRenderTargetTextures !== undefined) {
  24313. if (this._processedMaterials.indexOf(material) === -1) {
  24314. this._processedMaterials.push(material);
  24315. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24316. }
  24317. }
  24318. // Dispatch
  24319. this._activeIndices.addCount(subMesh.indexCount, false);
  24320. this._renderingManager.dispatch(subMesh, mesh, material);
  24321. }
  24322. }
  24323. };
  24324. /**
  24325. * Clear the processed materials smart array preventing retention point in material dispose.
  24326. */
  24327. Scene.prototype.freeProcessedMaterials = function () {
  24328. this._processedMaterials.dispose();
  24329. };
  24330. /**
  24331. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24332. */
  24333. Scene.prototype.freeActiveMeshes = function () {
  24334. this._activeMeshes.dispose();
  24335. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24336. this.activeCamera._activeMeshes.dispose();
  24337. }
  24338. if (this.activeCameras) {
  24339. for (var i = 0; i < this.activeCameras.length; i++) {
  24340. var activeCamera = this.activeCameras[i];
  24341. if (activeCamera && activeCamera._activeMeshes) {
  24342. activeCamera._activeMeshes.dispose();
  24343. }
  24344. }
  24345. }
  24346. };
  24347. /**
  24348. * Clear the info related to rendering groups preventing retention points during dispose.
  24349. */
  24350. Scene.prototype.freeRenderingGroups = function () {
  24351. if (this._renderingManager) {
  24352. this._renderingManager.freeRenderingGroups();
  24353. }
  24354. if (this.textures) {
  24355. for (var i = 0; i < this.textures.length; i++) {
  24356. var texture = this.textures[i];
  24357. if (texture && texture.renderList) {
  24358. texture.freeRenderingGroups();
  24359. }
  24360. }
  24361. }
  24362. };
  24363. Scene.prototype._isInIntermediateRendering = function () {
  24364. return this._intermediateRendering;
  24365. };
  24366. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24367. this._activeMeshCandidateProvider = provider;
  24368. };
  24369. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24370. return this._activeMeshCandidateProvider;
  24371. };
  24372. /**
  24373. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24374. */
  24375. Scene.prototype.freezeActiveMeshes = function () {
  24376. if (!this.activeCamera) {
  24377. return this;
  24378. }
  24379. if (!this._frustumPlanes) {
  24380. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24381. }
  24382. this._evaluateActiveMeshes();
  24383. this._activeMeshesFrozen = true;
  24384. return this;
  24385. };
  24386. /**
  24387. * Use this function to restart evaluating active meshes on every frame
  24388. */
  24389. Scene.prototype.unfreezeActiveMeshes = function () {
  24390. this._activeMeshesFrozen = false;
  24391. return this;
  24392. };
  24393. Scene.prototype._evaluateActiveMeshes = function () {
  24394. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24395. return;
  24396. }
  24397. if (!this.activeCamera) {
  24398. return;
  24399. }
  24400. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24401. this.activeCamera._activeMeshes.reset();
  24402. this._activeMeshes.reset();
  24403. this._renderingManager.reset();
  24404. this._processedMaterials.reset();
  24405. this._activeParticleSystems.reset();
  24406. this._activeSkeletons.reset();
  24407. this._softwareSkinnedMeshes.reset();
  24408. if (this._boundingBoxRenderer) {
  24409. this._boundingBoxRenderer.reset();
  24410. }
  24411. // Meshes
  24412. var meshes;
  24413. var len;
  24414. var checkIsEnabled = true;
  24415. // Determine mesh candidates
  24416. if (this._activeMeshCandidateProvider !== undefined) {
  24417. // Use _activeMeshCandidateProvider
  24418. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24419. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24420. if (meshes !== undefined) {
  24421. len = meshes.length;
  24422. }
  24423. else {
  24424. len = 0;
  24425. }
  24426. }
  24427. else if (this._selectionOctree !== undefined) {
  24428. // Octree
  24429. var selection = this._selectionOctree.select(this._frustumPlanes);
  24430. meshes = selection.data;
  24431. len = selection.length;
  24432. }
  24433. else {
  24434. // Full scene traversal
  24435. len = this.meshes.length;
  24436. meshes = this.meshes;
  24437. }
  24438. // Check each mesh
  24439. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24440. mesh = meshes[meshIndex];
  24441. if (mesh.isBlocked) {
  24442. continue;
  24443. }
  24444. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24445. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24446. continue;
  24447. }
  24448. mesh.computeWorldMatrix();
  24449. // Intersections
  24450. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24451. this._meshesForIntersections.pushNoDuplicate(mesh);
  24452. }
  24453. // Switch to current LOD
  24454. meshLOD = mesh.getLOD(this.activeCamera);
  24455. if (meshLOD === undefined || meshLOD === null) {
  24456. continue;
  24457. }
  24458. mesh._preActivate();
  24459. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24460. this._activeMeshes.push(mesh);
  24461. this.activeCamera._activeMeshes.push(mesh);
  24462. mesh._activate(this._renderId);
  24463. if (meshLOD !== mesh) {
  24464. meshLOD._activate(this._renderId);
  24465. }
  24466. this._activeMesh(mesh, meshLOD);
  24467. }
  24468. }
  24469. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24470. // Particle systems
  24471. if (this.particlesEnabled) {
  24472. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24473. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24474. var particleSystem = this.particleSystems[particleIndex];
  24475. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24476. continue;
  24477. }
  24478. var emitter = particleSystem.emitter;
  24479. if (!emitter.position || emitter.isEnabled()) {
  24480. this._activeParticleSystems.push(particleSystem);
  24481. particleSystem.animate();
  24482. this._renderingManager.dispatchParticles(particleSystem);
  24483. }
  24484. }
  24485. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24486. }
  24487. };
  24488. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24489. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24490. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24491. mesh.skeleton.prepare();
  24492. }
  24493. if (!mesh.computeBonesUsingShaders) {
  24494. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24495. }
  24496. }
  24497. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24498. var boundingInfo = sourceMesh.getBoundingInfo();
  24499. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24500. }
  24501. if (mesh !== undefined && mesh !== null
  24502. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24503. // Submeshes Octrees
  24504. var len;
  24505. var subMeshes;
  24506. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24507. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24508. len = intersections.length;
  24509. subMeshes = intersections.data;
  24510. }
  24511. else {
  24512. subMeshes = mesh.subMeshes;
  24513. len = subMeshes.length;
  24514. }
  24515. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24516. subMesh = subMeshes[subIndex];
  24517. this._evaluateSubMesh(subMesh, mesh);
  24518. }
  24519. }
  24520. };
  24521. Scene.prototype.updateTransformMatrix = function (force) {
  24522. if (!this.activeCamera) {
  24523. return;
  24524. }
  24525. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24526. };
  24527. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24528. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24529. };
  24530. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24531. if (camera && camera._skipRendering) {
  24532. return;
  24533. }
  24534. var engine = this._engine;
  24535. this.activeCamera = camera;
  24536. if (!this.activeCamera)
  24537. throw new Error("Active camera not set");
  24538. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24539. // Viewport
  24540. engine.setViewport(this.activeCamera.viewport);
  24541. // Camera
  24542. this.resetCachedMaterial();
  24543. this._renderId++;
  24544. this.updateTransformMatrix();
  24545. if (camera._alternateCamera) {
  24546. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24547. this._alternateRendering = true;
  24548. }
  24549. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24550. // Meshes
  24551. this._evaluateActiveMeshes();
  24552. // Software skinning
  24553. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24554. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24555. mesh.applySkeleton(mesh.skeleton);
  24556. }
  24557. // Render targets
  24558. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24559. var needsRestoreFrameBuffer = false;
  24560. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24561. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24562. }
  24563. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24564. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24565. }
  24566. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24567. this._intermediateRendering = true;
  24568. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24569. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24570. var renderTarget = this._renderTargets.data[renderIndex];
  24571. if (renderTarget._shouldRender()) {
  24572. this._renderId++;
  24573. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24574. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24575. }
  24576. }
  24577. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24578. this._intermediateRendering = false;
  24579. this._renderId++;
  24580. needsRestoreFrameBuffer = true; // Restore back buffer
  24581. }
  24582. // Render EffecttLayer Texture
  24583. var stencilState = this._engine.getStencilBuffer();
  24584. var renderEffects = false;
  24585. var needStencil = false;
  24586. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24587. this._intermediateRendering = true;
  24588. for (var i = 0; i < this.effectLayers.length; i++) {
  24589. var effectLayer = this.effectLayers[i];
  24590. if (effectLayer.shouldRender() &&
  24591. (!effectLayer.camera ||
  24592. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24593. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24594. renderEffects = true;
  24595. needStencil = needStencil || effectLayer.needStencil();
  24596. var renderTarget = effectLayer._mainTexture;
  24597. if (renderTarget._shouldRender()) {
  24598. this._renderId++;
  24599. renderTarget.render(false, false);
  24600. needsRestoreFrameBuffer = true;
  24601. }
  24602. }
  24603. }
  24604. this._intermediateRendering = false;
  24605. this._renderId++;
  24606. }
  24607. if (needsRestoreFrameBuffer) {
  24608. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24609. }
  24610. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24611. // Prepare Frame
  24612. this.postProcessManager._prepareFrame();
  24613. // Backgrounds
  24614. var layerIndex;
  24615. var layer;
  24616. if (this.layers.length) {
  24617. engine.setDepthBuffer(false);
  24618. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24619. layer = this.layers[layerIndex];
  24620. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24621. layer.render();
  24622. }
  24623. }
  24624. engine.setDepthBuffer(true);
  24625. }
  24626. // Activate effect Layer stencil
  24627. if (needStencil) {
  24628. this._engine.setStencilBuffer(true);
  24629. }
  24630. // Render
  24631. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24632. this._renderingManager.render(null, null, true, true);
  24633. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24634. // Restore effect Layer stencil
  24635. if (needStencil) {
  24636. this._engine.setStencilBuffer(stencilState);
  24637. }
  24638. // Bounding boxes
  24639. if (this._boundingBoxRenderer) {
  24640. this._boundingBoxRenderer.render();
  24641. }
  24642. // Lens flares
  24643. if (this.lensFlaresEnabled) {
  24644. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24645. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24646. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24647. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24648. lensFlareSystem.render();
  24649. }
  24650. }
  24651. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24652. }
  24653. // Foregrounds
  24654. if (this.layers.length) {
  24655. engine.setDepthBuffer(false);
  24656. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24657. layer = this.layers[layerIndex];
  24658. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24659. layer.render();
  24660. }
  24661. }
  24662. engine.setDepthBuffer(true);
  24663. }
  24664. // Effect Layer
  24665. if (renderEffects) {
  24666. engine.setDepthBuffer(false);
  24667. for (var i = 0; i < this.effectLayers.length; i++) {
  24668. if (this.effectLayers[i].shouldRender()) {
  24669. this.effectLayers[i].render();
  24670. }
  24671. }
  24672. engine.setDepthBuffer(true);
  24673. }
  24674. // Finalize frame
  24675. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24676. // Reset some special arrays
  24677. this._renderTargets.reset();
  24678. this._alternateRendering = false;
  24679. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24680. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24681. };
  24682. Scene.prototype._processSubCameras = function (camera) {
  24683. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24684. this._renderForCamera(camera);
  24685. return;
  24686. }
  24687. // rig cameras
  24688. for (var index = 0; index < camera._rigCameras.length; index++) {
  24689. this._renderForCamera(camera._rigCameras[index], camera);
  24690. }
  24691. this.activeCamera = camera;
  24692. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24693. };
  24694. Scene.prototype._checkIntersections = function () {
  24695. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24696. var sourceMesh = this._meshesForIntersections.data[index];
  24697. if (!sourceMesh.actionManager) {
  24698. continue;
  24699. }
  24700. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24701. var action = sourceMesh.actionManager.actions[actionIndex];
  24702. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24703. var parameters = action.getTriggerParameter();
  24704. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24705. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24706. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24707. if (areIntersecting && currentIntersectionInProgress === -1) {
  24708. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24709. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24710. sourceMesh._intersectionsInProgress.push(otherMesh);
  24711. }
  24712. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24713. sourceMesh._intersectionsInProgress.push(otherMesh);
  24714. }
  24715. }
  24716. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24717. //They intersected, and now they don't.
  24718. //is this trigger an exit trigger? execute an event.
  24719. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24720. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24721. }
  24722. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24723. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24724. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24725. }
  24726. }
  24727. }
  24728. }
  24729. }
  24730. };
  24731. Scene.prototype.render = function () {
  24732. if (this.isDisposed) {
  24733. return;
  24734. }
  24735. this._activeParticles.fetchNewFrame();
  24736. this._totalVertices.fetchNewFrame();
  24737. this._activeIndices.fetchNewFrame();
  24738. this._activeBones.fetchNewFrame();
  24739. this._meshesForIntersections.reset();
  24740. this.resetCachedMaterial();
  24741. this.onBeforeAnimationsObservable.notifyObservers(this);
  24742. // Actions
  24743. if (this.actionManager) {
  24744. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24745. }
  24746. //Simplification Queue
  24747. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24748. this.simplificationQueue.executeNext();
  24749. }
  24750. if (this._engine.isDeterministicLockStep()) {
  24751. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24752. var defaultFPS = (60.0 / 1000.0);
  24753. var defaultFrameTime = 1000 / 60; // frame time in MS
  24754. if (this._physicsEngine) {
  24755. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24756. }
  24757. var stepsTaken = 0;
  24758. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24759. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24760. internalSteps = Math.min(internalSteps, maxSubSteps);
  24761. do {
  24762. this.onBeforeStepObservable.notifyObservers(this);
  24763. // Animations
  24764. this._animationRatio = defaultFrameTime * defaultFPS;
  24765. this._animate();
  24766. this.onAfterAnimationsObservable.notifyObservers(this);
  24767. // Physics
  24768. if (this._physicsEngine) {
  24769. this.onBeforePhysicsObservable.notifyObservers(this);
  24770. this._physicsEngine._step(defaultFrameTime / 1000);
  24771. this.onAfterPhysicsObservable.notifyObservers(this);
  24772. }
  24773. this.onAfterStepObservable.notifyObservers(this);
  24774. this._currentStepId++;
  24775. stepsTaken++;
  24776. deltaTime -= defaultFrameTime;
  24777. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24778. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24779. }
  24780. else {
  24781. // Animations
  24782. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24783. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24784. this._animate();
  24785. this.onAfterAnimationsObservable.notifyObservers(this);
  24786. // Physics
  24787. if (this._physicsEngine) {
  24788. this.onBeforePhysicsObservable.notifyObservers(this);
  24789. this._physicsEngine._step(deltaTime / 1000.0);
  24790. this.onAfterPhysicsObservable.notifyObservers(this);
  24791. }
  24792. }
  24793. // update gamepad manager
  24794. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24795. this._gamepadManager._checkGamepadsStatus();
  24796. }
  24797. // Update Cameras
  24798. if (this.activeCameras.length > 0) {
  24799. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24800. var camera = this.activeCameras[cameraIndex];
  24801. camera.update();
  24802. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24803. // rig cameras
  24804. for (var index = 0; index < camera._rigCameras.length; index++) {
  24805. camera._rigCameras[index].update();
  24806. }
  24807. }
  24808. }
  24809. }
  24810. else if (this.activeCamera) {
  24811. this.activeCamera.update();
  24812. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24813. // rig cameras
  24814. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24815. this.activeCamera._rigCameras[index].update();
  24816. }
  24817. }
  24818. }
  24819. // Before render
  24820. this.onBeforeRenderObservable.notifyObservers(this);
  24821. // Customs render targets
  24822. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24823. var engine = this.getEngine();
  24824. var currentActiveCamera = this.activeCamera;
  24825. if (this.renderTargetsEnabled) {
  24826. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24827. this._intermediateRendering = true;
  24828. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24829. var renderTarget = this.customRenderTargets[customIndex];
  24830. if (renderTarget._shouldRender()) {
  24831. this._renderId++;
  24832. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24833. if (!this.activeCamera)
  24834. throw new Error("Active camera not set");
  24835. // Viewport
  24836. engine.setViewport(this.activeCamera.viewport);
  24837. // Camera
  24838. this.updateTransformMatrix();
  24839. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24840. }
  24841. }
  24842. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24843. this._intermediateRendering = false;
  24844. this._renderId++;
  24845. }
  24846. // Restore back buffer
  24847. if (this.customRenderTargets.length > 0) {
  24848. engine.restoreDefaultFramebuffer();
  24849. }
  24850. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24851. this.activeCamera = currentActiveCamera;
  24852. // Procedural textures
  24853. if (this.proceduralTexturesEnabled) {
  24854. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24855. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24856. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24857. if (proceduralTexture._shouldRender()) {
  24858. proceduralTexture.render();
  24859. }
  24860. }
  24861. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24862. }
  24863. // Clear
  24864. if (this.autoClearDepthAndStencil || this.autoClear) {
  24865. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24866. }
  24867. // Shadows
  24868. if (this.shadowsEnabled) {
  24869. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24870. var light = this.lights[lightIndex];
  24871. var shadowGenerator = light.getShadowGenerator();
  24872. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24873. var shadowMap = (shadowGenerator.getShadowMap());
  24874. if (this.textures.indexOf(shadowMap) !== -1) {
  24875. this._renderTargets.push(shadowMap);
  24876. }
  24877. }
  24878. }
  24879. }
  24880. // Depth renderer
  24881. for (var key in this._depthRenderer) {
  24882. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24883. }
  24884. // Geometry renderer
  24885. if (this._geometryBufferRenderer) {
  24886. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24887. }
  24888. // RenderPipeline
  24889. if (this._postProcessRenderPipelineManager) {
  24890. this._postProcessRenderPipelineManager.update();
  24891. }
  24892. // Multi-cameras?
  24893. if (this.activeCameras.length > 0) {
  24894. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24895. if (cameraIndex > 0) {
  24896. this._engine.clear(null, false, true, true);
  24897. }
  24898. this._processSubCameras(this.activeCameras[cameraIndex]);
  24899. }
  24900. }
  24901. else {
  24902. if (!this.activeCamera) {
  24903. throw new Error("No camera defined");
  24904. }
  24905. this._processSubCameras(this.activeCamera);
  24906. }
  24907. // Intersection checks
  24908. this._checkIntersections();
  24909. // Update the audio listener attached to the camera
  24910. if (BABYLON.AudioEngine) {
  24911. this._updateAudioParameters();
  24912. }
  24913. // After render
  24914. if (this.afterRender) {
  24915. this.afterRender();
  24916. }
  24917. this.onAfterRenderObservable.notifyObservers(this);
  24918. // Cleaning
  24919. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24920. var data = this._toBeDisposed.data[index];
  24921. if (data) {
  24922. data.dispose();
  24923. }
  24924. this._toBeDisposed[index] = null;
  24925. }
  24926. this._toBeDisposed.reset();
  24927. if (this.dumpNextRenderTargets) {
  24928. this.dumpNextRenderTargets = false;
  24929. }
  24930. this._activeBones.addCount(0, true);
  24931. this._activeIndices.addCount(0, true);
  24932. this._activeParticles.addCount(0, true);
  24933. };
  24934. Scene.prototype._updateAudioParameters = function () {
  24935. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24936. return;
  24937. }
  24938. var listeningCamera;
  24939. var audioEngine = BABYLON.Engine.audioEngine;
  24940. if (this.activeCameras.length > 0) {
  24941. listeningCamera = this.activeCameras[0];
  24942. }
  24943. else {
  24944. listeningCamera = this.activeCamera;
  24945. }
  24946. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24947. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24948. // for VR cameras
  24949. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24950. listeningCamera = listeningCamera.rigCameras[0];
  24951. }
  24952. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24953. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24954. cameraDirection.normalize();
  24955. // To avoid some errors on GearVR
  24956. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24957. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24958. }
  24959. var i;
  24960. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24961. var sound = this.mainSoundTrack.soundCollection[i];
  24962. if (sound.useCustomAttenuation) {
  24963. sound.updateDistanceFromListener();
  24964. }
  24965. }
  24966. for (i = 0; i < this.soundTracks.length; i++) {
  24967. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24968. sound = this.soundTracks[i].soundCollection[j];
  24969. if (sound.useCustomAttenuation) {
  24970. sound.updateDistanceFromListener();
  24971. }
  24972. }
  24973. }
  24974. }
  24975. };
  24976. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24977. // Audio
  24978. get: function () {
  24979. return this._audioEnabled;
  24980. },
  24981. set: function (value) {
  24982. this._audioEnabled = value;
  24983. if (BABYLON.AudioEngine) {
  24984. if (this._audioEnabled) {
  24985. this._enableAudio();
  24986. }
  24987. else {
  24988. this._disableAudio();
  24989. }
  24990. }
  24991. },
  24992. enumerable: true,
  24993. configurable: true
  24994. });
  24995. Scene.prototype._disableAudio = function () {
  24996. var i;
  24997. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24998. this.mainSoundTrack.soundCollection[i].pause();
  24999. }
  25000. for (i = 0; i < this.soundTracks.length; i++) {
  25001. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25002. this.soundTracks[i].soundCollection[j].pause();
  25003. }
  25004. }
  25005. };
  25006. Scene.prototype._enableAudio = function () {
  25007. var i;
  25008. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25009. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25010. this.mainSoundTrack.soundCollection[i].play();
  25011. }
  25012. }
  25013. for (i = 0; i < this.soundTracks.length; i++) {
  25014. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25015. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25016. this.soundTracks[i].soundCollection[j].play();
  25017. }
  25018. }
  25019. }
  25020. };
  25021. Object.defineProperty(Scene.prototype, "headphone", {
  25022. get: function () {
  25023. return this._headphone;
  25024. },
  25025. set: function (value) {
  25026. this._headphone = value;
  25027. if (BABYLON.AudioEngine) {
  25028. if (this._headphone) {
  25029. this._switchAudioModeForHeadphones();
  25030. }
  25031. else {
  25032. this._switchAudioModeForNormalSpeakers();
  25033. }
  25034. }
  25035. },
  25036. enumerable: true,
  25037. configurable: true
  25038. });
  25039. Scene.prototype._switchAudioModeForHeadphones = function () {
  25040. this.mainSoundTrack.switchPanningModelToHRTF();
  25041. for (var i = 0; i < this.soundTracks.length; i++) {
  25042. this.soundTracks[i].switchPanningModelToHRTF();
  25043. }
  25044. };
  25045. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25046. this.mainSoundTrack.switchPanningModelToEqualPower();
  25047. for (var i = 0; i < this.soundTracks.length; i++) {
  25048. this.soundTracks[i].switchPanningModelToEqualPower();
  25049. }
  25050. };
  25051. /**
  25052. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25053. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25054. * @returns the created depth renderer
  25055. */
  25056. Scene.prototype.enableDepthRenderer = function (camera) {
  25057. camera = camera || this.activeCamera;
  25058. if (!camera) {
  25059. throw "No camera available to enable depth renderer";
  25060. }
  25061. if (!this._depthRenderer[camera.id]) {
  25062. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  25063. }
  25064. return this._depthRenderer[camera.id];
  25065. };
  25066. /**
  25067. * Disables a depth renderer for a given camera
  25068. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25069. */
  25070. Scene.prototype.disableDepthRenderer = function (camera) {
  25071. camera = camera || this.activeCamera;
  25072. if (!camera || !this._depthRenderer[camera.id]) {
  25073. return;
  25074. }
  25075. this._depthRenderer[camera.id].dispose();
  25076. delete this._depthRenderer[camera.id];
  25077. };
  25078. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25079. if (ratio === void 0) { ratio = 1; }
  25080. if (this._geometryBufferRenderer) {
  25081. return this._geometryBufferRenderer;
  25082. }
  25083. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25084. if (!this._geometryBufferRenderer.isSupported) {
  25085. this._geometryBufferRenderer = null;
  25086. }
  25087. return this._geometryBufferRenderer;
  25088. };
  25089. Scene.prototype.disableGeometryBufferRenderer = function () {
  25090. if (!this._geometryBufferRenderer) {
  25091. return;
  25092. }
  25093. this._geometryBufferRenderer.dispose();
  25094. this._geometryBufferRenderer = null;
  25095. };
  25096. Scene.prototype.freezeMaterials = function () {
  25097. for (var i = 0; i < this.materials.length; i++) {
  25098. this.materials[i].freeze();
  25099. }
  25100. };
  25101. Scene.prototype.unfreezeMaterials = function () {
  25102. for (var i = 0; i < this.materials.length; i++) {
  25103. this.materials[i].unfreeze();
  25104. }
  25105. };
  25106. Scene.prototype.dispose = function () {
  25107. this.beforeRender = null;
  25108. this.afterRender = null;
  25109. this.skeletons = [];
  25110. this.morphTargetManagers = [];
  25111. this.importedMeshesFiles = new Array();
  25112. this.stopAllAnimations();
  25113. this.resetCachedMaterial();
  25114. for (var key in this._depthRenderer) {
  25115. this._depthRenderer[key].dispose();
  25116. }
  25117. if (this._gamepadManager) {
  25118. this._gamepadManager.dispose();
  25119. this._gamepadManager = null;
  25120. }
  25121. // Smart arrays
  25122. if (this.activeCamera) {
  25123. this.activeCamera._activeMeshes.dispose();
  25124. this.activeCamera = null;
  25125. }
  25126. this._activeMeshes.dispose();
  25127. this._renderingManager.dispose();
  25128. this._processedMaterials.dispose();
  25129. this._activeParticleSystems.dispose();
  25130. this._activeSkeletons.dispose();
  25131. this._softwareSkinnedMeshes.dispose();
  25132. this._renderTargets.dispose();
  25133. this._registeredForLateAnimationBindings.dispose();
  25134. if (this._boundingBoxRenderer) {
  25135. this._boundingBoxRenderer.dispose();
  25136. }
  25137. this._meshesForIntersections.dispose();
  25138. this._toBeDisposed.dispose();
  25139. // Abort active requests
  25140. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25141. var request = _a[_i];
  25142. request.abort();
  25143. }
  25144. // Debug layer
  25145. if (this._debugLayer) {
  25146. this._debugLayer.hide();
  25147. }
  25148. // Events
  25149. this.onDisposeObservable.notifyObservers(this);
  25150. this.onDisposeObservable.clear();
  25151. this.onBeforeRenderObservable.clear();
  25152. this.onAfterRenderObservable.clear();
  25153. this.OnBeforeRenderTargetsRenderObservable.clear();
  25154. this.OnAfterRenderTargetsRenderObservable.clear();
  25155. this.onAfterStepObservable.clear();
  25156. this.onBeforeStepObservable.clear();
  25157. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25158. this.onAfterActiveMeshesEvaluationObservable.clear();
  25159. this.onBeforeParticlesRenderingObservable.clear();
  25160. this.onAfterParticlesRenderingObservable.clear();
  25161. this.onBeforeSpritesRenderingObservable.clear();
  25162. this.onAfterSpritesRenderingObservable.clear();
  25163. this.onBeforeDrawPhaseObservable.clear();
  25164. this.onAfterDrawPhaseObservable.clear();
  25165. this.onBeforePhysicsObservable.clear();
  25166. this.onAfterPhysicsObservable.clear();
  25167. this.onBeforeAnimationsObservable.clear();
  25168. this.onAfterAnimationsObservable.clear();
  25169. this.onDataLoadedObservable.clear();
  25170. this.detachControl();
  25171. // Release sounds & sounds tracks
  25172. if (BABYLON.AudioEngine) {
  25173. this.disposeSounds();
  25174. }
  25175. // VR Helper
  25176. if (this.VRHelper) {
  25177. this.VRHelper.dispose();
  25178. }
  25179. // Detach cameras
  25180. var canvas = this._engine.getRenderingCanvas();
  25181. if (canvas) {
  25182. var index;
  25183. for (index = 0; index < this.cameras.length; index++) {
  25184. this.cameras[index].detachControl(canvas);
  25185. }
  25186. }
  25187. // Release animation groups
  25188. while (this.animationGroups.length) {
  25189. this.animationGroups[0].dispose();
  25190. }
  25191. // Release lights
  25192. while (this.lights.length) {
  25193. this.lights[0].dispose();
  25194. }
  25195. // Release meshes
  25196. while (this.meshes.length) {
  25197. this.meshes[0].dispose(true);
  25198. }
  25199. while (this.transformNodes.length) {
  25200. this.removeTransformNode(this.transformNodes[0]);
  25201. }
  25202. // Release cameras
  25203. while (this.cameras.length) {
  25204. this.cameras[0].dispose();
  25205. }
  25206. // Release materials
  25207. if (this.defaultMaterial) {
  25208. this.defaultMaterial.dispose();
  25209. }
  25210. while (this.multiMaterials.length) {
  25211. this.multiMaterials[0].dispose();
  25212. }
  25213. while (this.materials.length) {
  25214. this.materials[0].dispose();
  25215. }
  25216. // Release particles
  25217. while (this.particleSystems.length) {
  25218. this.particleSystems[0].dispose();
  25219. }
  25220. // Release sprites
  25221. while (this.spriteManagers.length) {
  25222. this.spriteManagers[0].dispose();
  25223. }
  25224. // Release postProcesses
  25225. while (this.postProcesses.length) {
  25226. this.postProcesses[0].dispose();
  25227. }
  25228. // Release layers
  25229. while (this.layers.length) {
  25230. this.layers[0].dispose();
  25231. }
  25232. while (this.effectLayers.length) {
  25233. this.effectLayers[0].dispose();
  25234. }
  25235. // Release textures
  25236. while (this.textures.length) {
  25237. this.textures[0].dispose();
  25238. }
  25239. // Release UBO
  25240. this._sceneUbo.dispose();
  25241. if (this._alternateSceneUbo) {
  25242. this._alternateSceneUbo.dispose();
  25243. }
  25244. // Post-processes
  25245. this.postProcessManager.dispose();
  25246. if (this._postProcessRenderPipelineManager) {
  25247. this._postProcessRenderPipelineManager.dispose();
  25248. }
  25249. // Physics
  25250. if (this._physicsEngine) {
  25251. this.disablePhysicsEngine();
  25252. }
  25253. // Remove from engine
  25254. index = this._engine.scenes.indexOf(this);
  25255. if (index > -1) {
  25256. this._engine.scenes.splice(index, 1);
  25257. }
  25258. this._engine.wipeCaches(true);
  25259. this._isDisposed = true;
  25260. };
  25261. Object.defineProperty(Scene.prototype, "isDisposed", {
  25262. get: function () {
  25263. return this._isDisposed;
  25264. },
  25265. enumerable: true,
  25266. configurable: true
  25267. });
  25268. // Release sounds & sounds tracks
  25269. Scene.prototype.disposeSounds = function () {
  25270. if (!this._mainSoundTrack) {
  25271. return;
  25272. }
  25273. this.mainSoundTrack.dispose();
  25274. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25275. this.soundTracks[scIndex].dispose();
  25276. }
  25277. };
  25278. // Octrees
  25279. /**
  25280. * Get the world extend vectors with an optional filter
  25281. *
  25282. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25283. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25284. */
  25285. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25286. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25287. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25288. filterPredicate = filterPredicate || (function () { return true; });
  25289. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25290. mesh.computeWorldMatrix(true);
  25291. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25292. return;
  25293. }
  25294. var boundingInfo = mesh.getBoundingInfo();
  25295. var minBox = boundingInfo.boundingBox.minimumWorld;
  25296. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25297. BABYLON.Tools.CheckExtends(minBox, min, max);
  25298. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25299. });
  25300. return {
  25301. min: min,
  25302. max: max
  25303. };
  25304. };
  25305. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25306. if (maxCapacity === void 0) { maxCapacity = 64; }
  25307. if (maxDepth === void 0) { maxDepth = 2; }
  25308. if (!this._selectionOctree) {
  25309. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25310. }
  25311. var worldExtends = this.getWorldExtends();
  25312. // Update octree
  25313. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25314. return this._selectionOctree;
  25315. };
  25316. // Picking
  25317. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25318. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25319. var result = BABYLON.Ray.Zero();
  25320. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25321. return result;
  25322. };
  25323. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25324. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25325. var engine = this._engine;
  25326. if (!camera) {
  25327. if (!this.activeCamera)
  25328. throw new Error("Active camera not set");
  25329. camera = this.activeCamera;
  25330. }
  25331. var cameraViewport = camera.viewport;
  25332. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25333. // Moving coordinates to local viewport world
  25334. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25335. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25336. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25337. return this;
  25338. };
  25339. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25340. var result = BABYLON.Ray.Zero();
  25341. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25342. return result;
  25343. };
  25344. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25345. if (!BABYLON.PickingInfo) {
  25346. return this;
  25347. }
  25348. var engine = this._engine;
  25349. if (!camera) {
  25350. if (!this.activeCamera)
  25351. throw new Error("Active camera not set");
  25352. camera = this.activeCamera;
  25353. }
  25354. var cameraViewport = camera.viewport;
  25355. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25356. var identity = BABYLON.Matrix.Identity();
  25357. // Moving coordinates to local viewport world
  25358. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25359. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25360. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25361. return this;
  25362. };
  25363. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25364. if (!BABYLON.PickingInfo) {
  25365. return null;
  25366. }
  25367. var pickingInfo = null;
  25368. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25369. var mesh = this.meshes[meshIndex];
  25370. if (predicate) {
  25371. if (!predicate(mesh)) {
  25372. continue;
  25373. }
  25374. }
  25375. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25376. continue;
  25377. }
  25378. var world = mesh.getWorldMatrix();
  25379. var ray = rayFunction(world);
  25380. var result = mesh.intersects(ray, fastCheck);
  25381. if (!result || !result.hit)
  25382. continue;
  25383. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25384. continue;
  25385. pickingInfo = result;
  25386. if (fastCheck) {
  25387. break;
  25388. }
  25389. }
  25390. return pickingInfo || new BABYLON.PickingInfo();
  25391. };
  25392. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25393. if (!BABYLON.PickingInfo) {
  25394. return null;
  25395. }
  25396. var pickingInfos = new Array();
  25397. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25398. var mesh = this.meshes[meshIndex];
  25399. if (predicate) {
  25400. if (!predicate(mesh)) {
  25401. continue;
  25402. }
  25403. }
  25404. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25405. continue;
  25406. }
  25407. var world = mesh.getWorldMatrix();
  25408. var ray = rayFunction(world);
  25409. var result = mesh.intersects(ray, false);
  25410. if (!result || !result.hit)
  25411. continue;
  25412. pickingInfos.push(result);
  25413. }
  25414. return pickingInfos;
  25415. };
  25416. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25417. if (!BABYLON.PickingInfo) {
  25418. return null;
  25419. }
  25420. var pickingInfo = null;
  25421. if (!camera) {
  25422. if (!this.activeCamera) {
  25423. return null;
  25424. }
  25425. camera = this.activeCamera;
  25426. }
  25427. if (this.spriteManagers.length > 0) {
  25428. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25429. var spriteManager = this.spriteManagers[spriteIndex];
  25430. if (!spriteManager.isPickable) {
  25431. continue;
  25432. }
  25433. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25434. if (!result || !result.hit)
  25435. continue;
  25436. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25437. continue;
  25438. pickingInfo = result;
  25439. if (fastCheck) {
  25440. break;
  25441. }
  25442. }
  25443. }
  25444. return pickingInfo || new BABYLON.PickingInfo();
  25445. };
  25446. /** Launch a ray to try to pick a mesh in the scene
  25447. * @param x position on screen
  25448. * @param y position on screen
  25449. * @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
  25450. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25451. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25452. */
  25453. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25454. var _this = this;
  25455. if (!BABYLON.PickingInfo) {
  25456. return null;
  25457. }
  25458. return this._internalPick(function (world) {
  25459. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25460. return _this._tempPickingRay;
  25461. }, predicate, fastCheck);
  25462. };
  25463. /** Launch a ray to try to pick a sprite in the scene
  25464. * @param x position on screen
  25465. * @param y position on screen
  25466. * @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
  25467. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25468. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25469. */
  25470. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25471. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25472. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25473. };
  25474. /** Use the given ray to pick a mesh in the scene
  25475. * @param ray The ray to use to pick meshes
  25476. * @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
  25477. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25478. */
  25479. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25480. var _this = this;
  25481. return this._internalPick(function (world) {
  25482. if (!_this._pickWithRayInverseMatrix) {
  25483. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25484. }
  25485. world.invertToRef(_this._pickWithRayInverseMatrix);
  25486. if (!_this._cachedRayForTransform) {
  25487. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25488. }
  25489. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25490. return _this._cachedRayForTransform;
  25491. }, predicate, fastCheck);
  25492. };
  25493. /**
  25494. * Launch a ray to try to pick a mesh in the scene
  25495. * @param x X position on screen
  25496. * @param y Y position on screen
  25497. * @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
  25498. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25499. */
  25500. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25501. var _this = this;
  25502. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25503. };
  25504. /**
  25505. * Launch a ray to try to pick a mesh in the scene
  25506. * @param ray Ray to use
  25507. * @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
  25508. */
  25509. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25510. var _this = this;
  25511. return this._internalMultiPick(function (world) {
  25512. if (!_this._pickWithRayInverseMatrix) {
  25513. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25514. }
  25515. world.invertToRef(_this._pickWithRayInverseMatrix);
  25516. if (!_this._cachedRayForTransform) {
  25517. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25518. }
  25519. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25520. return _this._cachedRayForTransform;
  25521. }, predicate);
  25522. };
  25523. Scene.prototype.setPointerOverMesh = function (mesh) {
  25524. if (this._pointerOverMesh === mesh) {
  25525. return;
  25526. }
  25527. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25528. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25529. }
  25530. this._pointerOverMesh = mesh;
  25531. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25532. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25533. }
  25534. };
  25535. Scene.prototype.getPointerOverMesh = function () {
  25536. return this._pointerOverMesh;
  25537. };
  25538. Scene.prototype.setPointerOverSprite = function (sprite) {
  25539. if (this._pointerOverSprite === sprite) {
  25540. return;
  25541. }
  25542. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25543. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25544. }
  25545. this._pointerOverSprite = sprite;
  25546. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25547. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25548. }
  25549. };
  25550. Scene.prototype.getPointerOverSprite = function () {
  25551. return this._pointerOverSprite;
  25552. };
  25553. // Physics
  25554. Scene.prototype.getPhysicsEngine = function () {
  25555. return this._physicsEngine;
  25556. };
  25557. /**
  25558. * Enables physics to the current scene
  25559. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25560. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25561. * @return {boolean} was the physics engine initialized
  25562. */
  25563. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25564. if (gravity === void 0) { gravity = null; }
  25565. if (this._physicsEngine) {
  25566. return true;
  25567. }
  25568. try {
  25569. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25570. return true;
  25571. }
  25572. catch (e) {
  25573. BABYLON.Tools.Error(e.message);
  25574. return false;
  25575. }
  25576. };
  25577. Scene.prototype.disablePhysicsEngine = function () {
  25578. if (!this._physicsEngine) {
  25579. return;
  25580. }
  25581. this._physicsEngine.dispose();
  25582. this._physicsEngine = null;
  25583. };
  25584. Scene.prototype.isPhysicsEnabled = function () {
  25585. return this._physicsEngine !== undefined;
  25586. };
  25587. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25588. var mesh = compound.parts[0].mesh;
  25589. if (mesh.physicsImpostor) {
  25590. mesh.physicsImpostor.dispose();
  25591. mesh.physicsImpostor = null;
  25592. }
  25593. };
  25594. // Misc.
  25595. Scene.prototype._rebuildGeometries = function () {
  25596. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25597. var geometry = _a[_i];
  25598. geometry._rebuild();
  25599. }
  25600. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25601. var mesh = _c[_b];
  25602. mesh._rebuild();
  25603. }
  25604. if (this.postProcessManager) {
  25605. this.postProcessManager._rebuild();
  25606. }
  25607. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25608. var layer = _e[_d];
  25609. layer._rebuild();
  25610. }
  25611. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25612. var effectLayer = _g[_f];
  25613. effectLayer._rebuild();
  25614. }
  25615. if (this._boundingBoxRenderer) {
  25616. this._boundingBoxRenderer._rebuild();
  25617. }
  25618. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25619. var system = _j[_h];
  25620. system.rebuild();
  25621. }
  25622. if (this._postProcessRenderPipelineManager) {
  25623. this._postProcessRenderPipelineManager._rebuild();
  25624. }
  25625. };
  25626. Scene.prototype._rebuildTextures = function () {
  25627. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25628. var texture = _a[_i];
  25629. texture._rebuild();
  25630. }
  25631. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25632. };
  25633. /**
  25634. * Creates a default light for the scene.
  25635. * @param replace Whether to replace the existing lights in the scene.
  25636. */
  25637. Scene.prototype.createDefaultLight = function (replace) {
  25638. if (replace === void 0) { replace = false; }
  25639. // Dispose existing light in replace mode.
  25640. if (replace) {
  25641. if (this.lights) {
  25642. for (var i = 0; i < this.lights.length; i++) {
  25643. this.lights[i].dispose();
  25644. }
  25645. }
  25646. }
  25647. // Light
  25648. if (this.lights.length === 0) {
  25649. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25650. }
  25651. };
  25652. /**
  25653. * Creates a default camera for the scene.
  25654. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25655. * @param replace Whether to replace the existing active camera in the scene.
  25656. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25657. */
  25658. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25659. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25660. if (replace === void 0) { replace = false; }
  25661. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25662. // Dispose existing camera in replace mode.
  25663. if (replace) {
  25664. if (this.activeCamera) {
  25665. this.activeCamera.dispose();
  25666. this.activeCamera = null;
  25667. }
  25668. }
  25669. // Camera
  25670. if (!this.activeCamera) {
  25671. var worldExtends = this.getWorldExtends();
  25672. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25673. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25674. var camera;
  25675. var radius = worldSize.length() * 1.5;
  25676. // empty scene scenario!
  25677. if (!isFinite(radius)) {
  25678. radius = 1;
  25679. worldCenter.copyFromFloats(0, 0, 0);
  25680. }
  25681. if (createArcRotateCamera) {
  25682. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25683. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25684. arcRotateCamera.wheelPrecision = 100 / radius;
  25685. camera = arcRotateCamera;
  25686. }
  25687. else {
  25688. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25689. freeCamera.setTarget(worldCenter);
  25690. camera = freeCamera;
  25691. }
  25692. camera.minZ = radius * 0.01;
  25693. camera.maxZ = radius * 1000;
  25694. camera.speed = radius * 0.2;
  25695. this.activeCamera = camera;
  25696. var canvas = this.getEngine().getRenderingCanvas();
  25697. if (attachCameraControls && canvas) {
  25698. camera.attachControl(canvas);
  25699. }
  25700. }
  25701. };
  25702. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25703. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25704. if (replace === void 0) { replace = false; }
  25705. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25706. this.createDefaultLight(replace);
  25707. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25708. };
  25709. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25710. if (pbr === void 0) { pbr = false; }
  25711. if (scale === void 0) { scale = 1000; }
  25712. if (blur === void 0) { blur = 0; }
  25713. if (environmentTexture) {
  25714. this.environmentTexture = environmentTexture;
  25715. }
  25716. if (!this.environmentTexture) {
  25717. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25718. return null;
  25719. }
  25720. // Skybox
  25721. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25722. if (pbr) {
  25723. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25724. hdrSkyboxMaterial.backFaceCulling = false;
  25725. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25726. if (hdrSkyboxMaterial.reflectionTexture) {
  25727. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25728. }
  25729. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25730. hdrSkyboxMaterial.disableLighting = true;
  25731. hdrSkyboxMaterial.twoSidedLighting = true;
  25732. hdrSkybox.infiniteDistance = true;
  25733. hdrSkybox.material = hdrSkyboxMaterial;
  25734. }
  25735. else {
  25736. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25737. skyboxMaterial.backFaceCulling = false;
  25738. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25739. if (skyboxMaterial.reflectionTexture) {
  25740. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25741. }
  25742. skyboxMaterial.disableLighting = true;
  25743. hdrSkybox.infiniteDistance = true;
  25744. hdrSkybox.material = skyboxMaterial;
  25745. }
  25746. return hdrSkybox;
  25747. };
  25748. Scene.prototype.createDefaultEnvironment = function (options) {
  25749. if (BABYLON.EnvironmentHelper) {
  25750. return new BABYLON.EnvironmentHelper(options, this);
  25751. }
  25752. return null;
  25753. };
  25754. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25755. if (webVROptions === void 0) { webVROptions = {}; }
  25756. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25757. };
  25758. // Tags
  25759. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25760. if (tagsQuery === undefined) {
  25761. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25762. return list;
  25763. }
  25764. var listByTags = [];
  25765. forEach = forEach || (function (item) { return; });
  25766. for (var i in list) {
  25767. var item = list[i];
  25768. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25769. listByTags.push(item);
  25770. forEach(item);
  25771. }
  25772. }
  25773. return listByTags;
  25774. };
  25775. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25776. return this._getByTags(this.meshes, tagsQuery, forEach);
  25777. };
  25778. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25779. return this._getByTags(this.cameras, tagsQuery, forEach);
  25780. };
  25781. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25782. return this._getByTags(this.lights, tagsQuery, forEach);
  25783. };
  25784. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25785. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25786. };
  25787. /**
  25788. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25789. * This allowed control for front to back rendering or reversly depending of the special needs.
  25790. *
  25791. * @param renderingGroupId The rendering group id corresponding to its index
  25792. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25793. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25794. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25795. */
  25796. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25797. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25798. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25799. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25800. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25801. };
  25802. /**
  25803. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25804. *
  25805. * @param renderingGroupId The rendering group id corresponding to its index
  25806. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25807. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25808. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25809. */
  25810. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25811. if (depth === void 0) { depth = true; }
  25812. if (stencil === void 0) { stencil = true; }
  25813. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25814. };
  25815. /**
  25816. * Will flag all materials as dirty to trigger new shader compilation
  25817. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25818. */
  25819. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25820. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25821. var material = _a[_i];
  25822. if (predicate && !predicate(material)) {
  25823. continue;
  25824. }
  25825. material.markAsDirty(flag);
  25826. }
  25827. };
  25828. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25829. var _this = this;
  25830. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25831. this._activeRequests.push(request);
  25832. request.onCompleteObservable.add(function (request) {
  25833. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25834. });
  25835. return request;
  25836. };
  25837. /** @ignore */
  25838. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25839. var _this = this;
  25840. return new Promise(function (resolve, reject) {
  25841. _this._loadFile(url, function (data) {
  25842. resolve(data);
  25843. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25844. reject(exception);
  25845. });
  25846. });
  25847. };
  25848. // Statics
  25849. Scene._FOGMODE_NONE = 0;
  25850. Scene._FOGMODE_EXP = 1;
  25851. Scene._FOGMODE_EXP2 = 2;
  25852. Scene._FOGMODE_LINEAR = 3;
  25853. Scene._uniqueIdCounter = 0;
  25854. Scene.MinDeltaTime = 1.0;
  25855. Scene.MaxDeltaTime = 1000.0;
  25856. /** The distance in pixel that you have to move to prevent some events */
  25857. Scene.DragMovementThreshold = 10; // in pixels
  25858. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25859. Scene.LongPressDelay = 500; // in milliseconds
  25860. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25861. Scene.DoubleClickDelay = 300; // in milliseconds
  25862. /** If you need to check double click without raising a single click at first click, enable this flag */
  25863. Scene.ExclusiveDoubleClickMode = false;
  25864. return Scene;
  25865. }());
  25866. BABYLON.Scene = Scene;
  25867. })(BABYLON || (BABYLON = {}));
  25868. //# sourceMappingURL=babylon.scene.js.map
  25869. "use strict";
  25870. var BABYLON;
  25871. (function (BABYLON) {
  25872. /**
  25873. * Set of assets to keep when moving a scene into an asset container.
  25874. */
  25875. var KeepAssets = /** @class */ (function () {
  25876. function KeepAssets() {
  25877. /**
  25878. * Cameras to keep.
  25879. */
  25880. this.cameras = new Array();
  25881. /**
  25882. * Lights to keep.
  25883. */
  25884. this.lights = new Array();
  25885. /**
  25886. * Meshes to keep.
  25887. */
  25888. this.meshes = new Array();
  25889. /**
  25890. * Skeletons to keep.
  25891. */
  25892. this.skeletons = new Array();
  25893. /**
  25894. * ParticleSystems to keep.
  25895. */
  25896. this.particleSystems = new Array();
  25897. /**
  25898. * Animations to keep.
  25899. */
  25900. this.animations = new Array();
  25901. /**
  25902. * MultiMaterials to keep.
  25903. */
  25904. this.multiMaterials = new Array();
  25905. /**
  25906. * Materials to keep.
  25907. */
  25908. this.materials = new Array();
  25909. /**
  25910. * MorphTargetManagers to keep.
  25911. */
  25912. this.morphTargetManagers = new Array();
  25913. /**
  25914. * Geometries to keep.
  25915. */
  25916. this.geometries = new Array();
  25917. /**
  25918. * TransformNodes to keep.
  25919. */
  25920. this.transformNodes = new Array();
  25921. /**
  25922. * LensFlareSystems to keep.
  25923. */
  25924. this.lensFlareSystems = new Array();
  25925. /**
  25926. * ShadowGenerators to keep.
  25927. */
  25928. this.shadowGenerators = new Array();
  25929. /**
  25930. * ActionManagers to keep.
  25931. */
  25932. this.actionManagers = new Array();
  25933. /**
  25934. * Sounds to keep.
  25935. */
  25936. this.sounds = new Array();
  25937. }
  25938. return KeepAssets;
  25939. }());
  25940. BABYLON.KeepAssets = KeepAssets;
  25941. /**
  25942. * Container with a set of assets that can be added or removed from a scene.
  25943. */
  25944. var AssetContainer = /** @class */ (function () {
  25945. /**
  25946. * Instantiates an AssetContainer.
  25947. * @param scene The scene the AssetContainer belongs to.
  25948. */
  25949. function AssetContainer(scene) {
  25950. // Objects
  25951. /**
  25952. * Cameras populated in the container.
  25953. */
  25954. this.cameras = new Array();
  25955. /**
  25956. * Lights populated in the container.
  25957. */
  25958. this.lights = new Array();
  25959. /**
  25960. * Meshes populated in the container.
  25961. */
  25962. this.meshes = new Array();
  25963. /**
  25964. * Skeletons populated in the container.
  25965. */
  25966. this.skeletons = new Array();
  25967. /**
  25968. * ParticleSystems populated in the container.
  25969. */
  25970. this.particleSystems = new Array();
  25971. /**
  25972. * Animations populated in the container.
  25973. */
  25974. this.animations = new Array();
  25975. /**
  25976. * MultiMaterials populated in the container.
  25977. */
  25978. this.multiMaterials = new Array();
  25979. /**
  25980. * Materials populated in the container.
  25981. */
  25982. this.materials = new Array();
  25983. /**
  25984. * MorphTargetManagers populated in the container.
  25985. */
  25986. this.morphTargetManagers = new Array();
  25987. /**
  25988. * Geometries populated in the container.
  25989. */
  25990. this.geometries = new Array();
  25991. /**
  25992. * TransformNodes populated in the container.
  25993. */
  25994. this.transformNodes = new Array();
  25995. /**
  25996. * LensFlareSystems populated in the container.
  25997. */
  25998. this.lensFlareSystems = new Array();
  25999. /**
  26000. * ShadowGenerators populated in the container.
  26001. */
  26002. this.shadowGenerators = new Array();
  26003. /**
  26004. * ActionManagers populated in the container.
  26005. */
  26006. this.actionManagers = new Array();
  26007. /**
  26008. * Sounds populated in the container.
  26009. */
  26010. this.sounds = new Array();
  26011. this.scene = scene;
  26012. }
  26013. /**
  26014. * Adds all the assets from the container to the scene.
  26015. */
  26016. AssetContainer.prototype.addAllToScene = function () {
  26017. var _this = this;
  26018. this.cameras.forEach(function (o) {
  26019. _this.scene.addCamera(o);
  26020. });
  26021. this.lights.forEach(function (o) {
  26022. _this.scene.addLight(o);
  26023. });
  26024. this.meshes.forEach(function (o) {
  26025. _this.scene.addMesh(o);
  26026. });
  26027. this.skeletons.forEach(function (o) {
  26028. _this.scene.addSkeleton(o);
  26029. });
  26030. this.particleSystems.forEach(function (o) {
  26031. _this.scene.addParticleSystem(o);
  26032. });
  26033. this.animations.forEach(function (o) {
  26034. _this.scene.addAnimation(o);
  26035. });
  26036. this.multiMaterials.forEach(function (o) {
  26037. _this.scene.addMultiMaterial(o);
  26038. });
  26039. this.materials.forEach(function (o) {
  26040. _this.scene.addMaterial(o);
  26041. });
  26042. this.morphTargetManagers.forEach(function (o) {
  26043. _this.scene.addMorphTargetManager(o);
  26044. });
  26045. this.geometries.forEach(function (o) {
  26046. _this.scene.addGeometry(o);
  26047. });
  26048. this.transformNodes.forEach(function (o) {
  26049. _this.scene.addTransformNode(o);
  26050. });
  26051. this.lensFlareSystems.forEach(function (o) {
  26052. _this.scene.addLensFlareSystem(o);
  26053. });
  26054. this.actionManagers.forEach(function (o) {
  26055. _this.scene.addActionManager(o);
  26056. });
  26057. this.sounds.forEach(function (o) {
  26058. o.play();
  26059. o.autoplay = true;
  26060. _this.scene.mainSoundTrack.AddSound(o);
  26061. });
  26062. };
  26063. /**
  26064. * Removes all the assets in the container from the scene
  26065. */
  26066. AssetContainer.prototype.removeAllFromScene = function () {
  26067. var _this = this;
  26068. this.cameras.forEach(function (o) {
  26069. _this.scene.removeCamera(o);
  26070. });
  26071. this.lights.forEach(function (o) {
  26072. _this.scene.removeLight(o);
  26073. });
  26074. this.meshes.forEach(function (o) {
  26075. _this.scene.removeMesh(o);
  26076. });
  26077. this.skeletons.forEach(function (o) {
  26078. _this.scene.removeSkeleton(o);
  26079. });
  26080. this.particleSystems.forEach(function (o) {
  26081. _this.scene.removeParticleSystem(o);
  26082. });
  26083. this.animations.forEach(function (o) {
  26084. _this.scene.removeAnimation(o);
  26085. });
  26086. this.multiMaterials.forEach(function (o) {
  26087. _this.scene.removeMultiMaterial(o);
  26088. });
  26089. this.materials.forEach(function (o) {
  26090. _this.scene.removeMaterial(o);
  26091. });
  26092. this.morphTargetManagers.forEach(function (o) {
  26093. _this.scene.removeMorphTargetManager(o);
  26094. });
  26095. this.geometries.forEach(function (o) {
  26096. _this.scene.removeGeometry(o);
  26097. });
  26098. this.transformNodes.forEach(function (o) {
  26099. _this.scene.removeTransformNode(o);
  26100. });
  26101. this.lensFlareSystems.forEach(function (o) {
  26102. _this.scene.removeLensFlareSystem(o);
  26103. });
  26104. this.actionManagers.forEach(function (o) {
  26105. _this.scene.removeActionManager(o);
  26106. });
  26107. this.sounds.forEach(function (o) {
  26108. o.stop();
  26109. o.autoplay = false;
  26110. _this.scene.mainSoundTrack.RemoveSound(o);
  26111. });
  26112. };
  26113. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26114. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26115. var asset = sourceAssets_1[_i];
  26116. var move = true;
  26117. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26118. var keepAsset = keepAssets_1[_a];
  26119. if (asset === keepAsset) {
  26120. move = false;
  26121. break;
  26122. }
  26123. }
  26124. if (move) {
  26125. targetAssets.push(asset);
  26126. }
  26127. }
  26128. };
  26129. /**
  26130. * Removes all the assets contained in the scene and adds them to the container.
  26131. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26132. */
  26133. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26134. if (keepAssets === undefined) {
  26135. keepAssets = new KeepAssets();
  26136. }
  26137. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26138. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26139. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26140. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26141. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26142. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26143. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26144. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26145. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26146. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26147. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26148. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26149. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26150. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26151. this.removeAllFromScene();
  26152. };
  26153. return AssetContainer;
  26154. }());
  26155. BABYLON.AssetContainer = AssetContainer;
  26156. })(BABYLON || (BABYLON = {}));
  26157. //# sourceMappingURL=babylon.assetContainer.js.map
  26158. "use strict";
  26159. var BABYLON;
  26160. (function (BABYLON) {
  26161. var Buffer = /** @class */ (function () {
  26162. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26163. if (instanced === void 0) { instanced = false; }
  26164. if (engine instanceof BABYLON.Mesh) {
  26165. this._engine = engine.getScene().getEngine();
  26166. }
  26167. else {
  26168. this._engine = engine;
  26169. }
  26170. this._updatable = updatable;
  26171. this._instanced = instanced;
  26172. this._data = data;
  26173. this._strideSize = stride;
  26174. if (!postponeInternalCreation) {
  26175. this.create();
  26176. }
  26177. }
  26178. /**
  26179. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26180. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26181. * @param offset defines offset in the buffer (0 by default)
  26182. * @param size defines the size in floats of attributes (position is 3 for instance)
  26183. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26184. * @param instanced defines if the vertex buffer contains indexed data
  26185. * @returns the new vertex buffer
  26186. */
  26187. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26188. // a lot of these parameters are ignored as they are overriden by the buffer
  26189. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26190. };
  26191. // Properties
  26192. Buffer.prototype.isUpdatable = function () {
  26193. return this._updatable;
  26194. };
  26195. Buffer.prototype.getData = function () {
  26196. return this._data;
  26197. };
  26198. Buffer.prototype.getBuffer = function () {
  26199. return this._buffer;
  26200. };
  26201. Buffer.prototype.getStrideSize = function () {
  26202. return this._strideSize;
  26203. };
  26204. // public getIsInstanced(): boolean {
  26205. // return this._instanced;
  26206. // }
  26207. // public get instanceDivisor(): number {
  26208. // return this._instanceDivisor;
  26209. // }
  26210. // public set instanceDivisor(value: number) {
  26211. // this._instanceDivisor = value;
  26212. // if (value == 0) {
  26213. // this._instanced = false;
  26214. // } else {
  26215. // this._instanced = true;
  26216. // }
  26217. // }
  26218. // Methods
  26219. Buffer.prototype.create = function (data) {
  26220. if (data === void 0) { data = null; }
  26221. if (!data && this._buffer) {
  26222. return; // nothing to do
  26223. }
  26224. data = data || this._data;
  26225. if (!data) {
  26226. return;
  26227. }
  26228. if (!this._buffer) {
  26229. if (this._updatable) {
  26230. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26231. this._data = data;
  26232. }
  26233. else {
  26234. this._buffer = this._engine.createVertexBuffer(data);
  26235. }
  26236. }
  26237. else if (this._updatable) {
  26238. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26239. this._data = data;
  26240. }
  26241. };
  26242. Buffer.prototype._rebuild = function () {
  26243. this._buffer = null;
  26244. this.create(this._data);
  26245. };
  26246. Buffer.prototype.update = function (data) {
  26247. this.create(data);
  26248. };
  26249. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26250. if (!this._buffer) {
  26251. return;
  26252. }
  26253. if (this._updatable) {
  26254. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26255. this._data = null;
  26256. }
  26257. };
  26258. Buffer.prototype.dispose = function () {
  26259. if (!this._buffer) {
  26260. return;
  26261. }
  26262. if (this._engine._releaseBuffer(this._buffer)) {
  26263. this._buffer = null;
  26264. }
  26265. };
  26266. return Buffer;
  26267. }());
  26268. BABYLON.Buffer = Buffer;
  26269. })(BABYLON || (BABYLON = {}));
  26270. //# sourceMappingURL=babylon.buffer.js.map
  26271. "use strict";
  26272. var BABYLON;
  26273. (function (BABYLON) {
  26274. var VertexBuffer = /** @class */ (function () {
  26275. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26276. if (data instanceof BABYLON.Buffer) {
  26277. if (!stride) {
  26278. stride = data.getStrideSize();
  26279. }
  26280. this._buffer = data;
  26281. this._ownsBuffer = false;
  26282. }
  26283. else {
  26284. if (!stride) {
  26285. stride = VertexBuffer.DeduceStride(kind);
  26286. }
  26287. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26288. this._ownsBuffer = true;
  26289. }
  26290. this._stride = stride;
  26291. this._instanced = instanced !== undefined ? instanced : false;
  26292. this._instanceDivisor = instanced ? 1 : 0;
  26293. this._offset = offset ? offset : 0;
  26294. this._size = size ? size : stride;
  26295. this._kind = kind;
  26296. }
  26297. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26298. /**
  26299. * Gets or sets the instance divisor when in instanced mode
  26300. */
  26301. get: function () {
  26302. return this._instanceDivisor;
  26303. },
  26304. set: function (value) {
  26305. this._instanceDivisor = value;
  26306. if (value == 0) {
  26307. this._instanced = false;
  26308. }
  26309. else {
  26310. this._instanced = true;
  26311. }
  26312. },
  26313. enumerable: true,
  26314. configurable: true
  26315. });
  26316. VertexBuffer.prototype._rebuild = function () {
  26317. if (!this._buffer) {
  26318. return;
  26319. }
  26320. this._buffer._rebuild();
  26321. };
  26322. /**
  26323. * Returns the kind of the VertexBuffer (string).
  26324. */
  26325. VertexBuffer.prototype.getKind = function () {
  26326. return this._kind;
  26327. };
  26328. // Properties
  26329. /**
  26330. * Boolean : is the VertexBuffer updatable ?
  26331. */
  26332. VertexBuffer.prototype.isUpdatable = function () {
  26333. return this._buffer.isUpdatable();
  26334. };
  26335. /**
  26336. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26337. */
  26338. VertexBuffer.prototype.getData = function () {
  26339. return this._buffer.getData();
  26340. };
  26341. /**
  26342. * Returns the WebGLBuffer associated to the VertexBuffer.
  26343. */
  26344. VertexBuffer.prototype.getBuffer = function () {
  26345. return this._buffer.getBuffer();
  26346. };
  26347. /**
  26348. * Returns the stride of the VertexBuffer (integer).
  26349. */
  26350. VertexBuffer.prototype.getStrideSize = function () {
  26351. return this._stride;
  26352. };
  26353. /**
  26354. * Returns the offset (integer).
  26355. */
  26356. VertexBuffer.prototype.getOffset = function () {
  26357. return this._offset;
  26358. };
  26359. /**
  26360. * Returns the VertexBuffer total size (integer).
  26361. */
  26362. VertexBuffer.prototype.getSize = function () {
  26363. return this._size;
  26364. };
  26365. /**
  26366. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26367. */
  26368. VertexBuffer.prototype.getIsInstanced = function () {
  26369. return this._instanced;
  26370. };
  26371. /**
  26372. * Returns the instancing divisor, zero for non-instanced (integer).
  26373. */
  26374. VertexBuffer.prototype.getInstanceDivisor = function () {
  26375. return this._instanceDivisor;
  26376. };
  26377. // Methods
  26378. /**
  26379. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26380. * Returns the created WebGLBuffer.
  26381. */
  26382. VertexBuffer.prototype.create = function (data) {
  26383. return this._buffer.create(data);
  26384. };
  26385. /**
  26386. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26387. * This function will create a new buffer if the current one is not updatable
  26388. * Returns the updated WebGLBuffer.
  26389. */
  26390. VertexBuffer.prototype.update = function (data) {
  26391. return this._buffer.update(data);
  26392. };
  26393. /**
  26394. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26395. * Returns the directly updated WebGLBuffer.
  26396. */
  26397. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26398. return this._buffer.updateDirectly(data, offset);
  26399. };
  26400. /**
  26401. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26402. */
  26403. VertexBuffer.prototype.dispose = function () {
  26404. if (this._ownsBuffer) {
  26405. this._buffer.dispose();
  26406. }
  26407. };
  26408. Object.defineProperty(VertexBuffer, "PositionKind", {
  26409. get: function () {
  26410. return VertexBuffer._PositionKind;
  26411. },
  26412. enumerable: true,
  26413. configurable: true
  26414. });
  26415. Object.defineProperty(VertexBuffer, "NormalKind", {
  26416. get: function () {
  26417. return VertexBuffer._NormalKind;
  26418. },
  26419. enumerable: true,
  26420. configurable: true
  26421. });
  26422. Object.defineProperty(VertexBuffer, "TangentKind", {
  26423. get: function () {
  26424. return VertexBuffer._TangentKind;
  26425. },
  26426. enumerable: true,
  26427. configurable: true
  26428. });
  26429. Object.defineProperty(VertexBuffer, "UVKind", {
  26430. get: function () {
  26431. return VertexBuffer._UVKind;
  26432. },
  26433. enumerable: true,
  26434. configurable: true
  26435. });
  26436. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26437. get: function () {
  26438. return VertexBuffer._UV2Kind;
  26439. },
  26440. enumerable: true,
  26441. configurable: true
  26442. });
  26443. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26444. get: function () {
  26445. return VertexBuffer._UV3Kind;
  26446. },
  26447. enumerable: true,
  26448. configurable: true
  26449. });
  26450. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26451. get: function () {
  26452. return VertexBuffer._UV4Kind;
  26453. },
  26454. enumerable: true,
  26455. configurable: true
  26456. });
  26457. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26458. get: function () {
  26459. return VertexBuffer._UV5Kind;
  26460. },
  26461. enumerable: true,
  26462. configurable: true
  26463. });
  26464. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26465. get: function () {
  26466. return VertexBuffer._UV6Kind;
  26467. },
  26468. enumerable: true,
  26469. configurable: true
  26470. });
  26471. Object.defineProperty(VertexBuffer, "ColorKind", {
  26472. get: function () {
  26473. return VertexBuffer._ColorKind;
  26474. },
  26475. enumerable: true,
  26476. configurable: true
  26477. });
  26478. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26479. get: function () {
  26480. return VertexBuffer._MatricesIndicesKind;
  26481. },
  26482. enumerable: true,
  26483. configurable: true
  26484. });
  26485. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26486. get: function () {
  26487. return VertexBuffer._MatricesWeightsKind;
  26488. },
  26489. enumerable: true,
  26490. configurable: true
  26491. });
  26492. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26493. get: function () {
  26494. return VertexBuffer._MatricesIndicesExtraKind;
  26495. },
  26496. enumerable: true,
  26497. configurable: true
  26498. });
  26499. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26500. get: function () {
  26501. return VertexBuffer._MatricesWeightsExtraKind;
  26502. },
  26503. enumerable: true,
  26504. configurable: true
  26505. });
  26506. /**
  26507. * Deduces the stride given a kind.
  26508. * @param kind The kind string to deduce
  26509. * @returns The deduced stride
  26510. */
  26511. VertexBuffer.DeduceStride = function (kind) {
  26512. switch (kind) {
  26513. case VertexBuffer.UVKind:
  26514. case VertexBuffer.UV2Kind:
  26515. case VertexBuffer.UV3Kind:
  26516. case VertexBuffer.UV4Kind:
  26517. case VertexBuffer.UV5Kind:
  26518. case VertexBuffer.UV6Kind:
  26519. return 2;
  26520. case VertexBuffer.NormalKind:
  26521. case VertexBuffer.PositionKind:
  26522. return 3;
  26523. case VertexBuffer.ColorKind:
  26524. case VertexBuffer.MatricesIndicesKind:
  26525. case VertexBuffer.MatricesIndicesExtraKind:
  26526. case VertexBuffer.MatricesWeightsKind:
  26527. case VertexBuffer.MatricesWeightsExtraKind:
  26528. case VertexBuffer.TangentKind:
  26529. return 4;
  26530. default:
  26531. throw new Error("Invalid kind '" + kind + "'");
  26532. }
  26533. };
  26534. // Enums
  26535. VertexBuffer._PositionKind = "position";
  26536. VertexBuffer._NormalKind = "normal";
  26537. VertexBuffer._TangentKind = "tangent";
  26538. VertexBuffer._UVKind = "uv";
  26539. VertexBuffer._UV2Kind = "uv2";
  26540. VertexBuffer._UV3Kind = "uv3";
  26541. VertexBuffer._UV4Kind = "uv4";
  26542. VertexBuffer._UV5Kind = "uv5";
  26543. VertexBuffer._UV6Kind = "uv6";
  26544. VertexBuffer._ColorKind = "color";
  26545. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26546. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26547. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26548. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26549. return VertexBuffer;
  26550. }());
  26551. BABYLON.VertexBuffer = VertexBuffer;
  26552. })(BABYLON || (BABYLON = {}));
  26553. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26554. "use strict";
  26555. var BABYLON;
  26556. (function (BABYLON) {
  26557. /**
  26558. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26559. */
  26560. var DummyInternalTextureTracker = /** @class */ (function () {
  26561. function DummyInternalTextureTracker() {
  26562. /**
  26563. * Gets or set the previous tracker in the list
  26564. */
  26565. this.previous = null;
  26566. /**
  26567. * Gets or set the next tracker in the list
  26568. */
  26569. this.next = null;
  26570. }
  26571. return DummyInternalTextureTracker;
  26572. }());
  26573. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26574. })(BABYLON || (BABYLON = {}));
  26575. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26576. "use strict";
  26577. var BABYLON;
  26578. (function (BABYLON) {
  26579. /**
  26580. * Class used to store data associated with WebGL texture data for the engine
  26581. * This class should not be used directly
  26582. */
  26583. var InternalTexture = /** @class */ (function () {
  26584. /**
  26585. * Creates a new InternalTexture
  26586. * @param engine defines the engine to use
  26587. * @param dataSource defines the type of data that will be used
  26588. */
  26589. function InternalTexture(engine, dataSource) {
  26590. /**
  26591. * Observable called when the texture is loaded
  26592. */
  26593. this.onLoadedObservable = new BABYLON.Observable();
  26594. /**
  26595. * Gets or set the previous tracker in the list
  26596. */
  26597. this.previous = null;
  26598. /**
  26599. * Gets or set the next tracker in the list
  26600. */
  26601. this.next = null;
  26602. // Private
  26603. /** @ignore */
  26604. this._initialSlot = -1;
  26605. /** @ignore */
  26606. this._designatedSlot = -1;
  26607. /** @ignore */
  26608. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26609. /** @ignore */
  26610. this._comparisonFunction = 0;
  26611. /** @ignore */
  26612. this._references = 1;
  26613. this._engine = engine;
  26614. this._dataSource = dataSource;
  26615. this._webGLTexture = engine._createTexture();
  26616. }
  26617. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26618. /**
  26619. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26620. */
  26621. get: function () {
  26622. return this._dataSource;
  26623. },
  26624. enumerable: true,
  26625. configurable: true
  26626. });
  26627. /**
  26628. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26629. */
  26630. InternalTexture.prototype.incrementReferences = function () {
  26631. this._references++;
  26632. };
  26633. /**
  26634. * Change the size of the texture (not the size of the content)
  26635. * @param width defines the new width
  26636. * @param height defines the new height
  26637. * @param depth defines the new depth (1 by default)
  26638. */
  26639. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26640. if (depth === void 0) { depth = 1; }
  26641. this.width = width;
  26642. this.height = height;
  26643. this.depth = depth;
  26644. this.baseWidth = width;
  26645. this.baseHeight = height;
  26646. this.baseDepth = depth;
  26647. this._size = width * height * depth;
  26648. };
  26649. /** @ignore */
  26650. InternalTexture.prototype._rebuild = function () {
  26651. var _this = this;
  26652. var proxy;
  26653. this.isReady = false;
  26654. this._cachedCoordinatesMode = null;
  26655. this._cachedWrapU = null;
  26656. this._cachedWrapV = null;
  26657. this._cachedAnisotropicFilteringLevel = null;
  26658. switch (this._dataSource) {
  26659. case InternalTexture.DATASOURCE_TEMP:
  26660. return;
  26661. case InternalTexture.DATASOURCE_URL:
  26662. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26663. _this.isReady = true;
  26664. }, null, this._buffer, undefined, this.format);
  26665. proxy._swapAndDie(this);
  26666. return;
  26667. case InternalTexture.DATASOURCE_RAW:
  26668. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26669. proxy._swapAndDie(this);
  26670. this.isReady = true;
  26671. return;
  26672. case InternalTexture.DATASOURCE_RAW3D:
  26673. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26674. proxy._swapAndDie(this);
  26675. this.isReady = true;
  26676. return;
  26677. case InternalTexture.DATASOURCE_DYNAMIC:
  26678. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26679. proxy._swapAndDie(this);
  26680. // The engine will make sure to update content so no need to flag it as isReady = true
  26681. return;
  26682. case InternalTexture.DATASOURCE_RENDERTARGET:
  26683. var options = new BABYLON.RenderTargetCreationOptions();
  26684. options.generateDepthBuffer = this._generateDepthBuffer;
  26685. options.generateMipMaps = this.generateMipMaps;
  26686. options.generateStencilBuffer = this._generateStencilBuffer;
  26687. options.samplingMode = this.samplingMode;
  26688. options.type = this.type;
  26689. if (this.isCube) {
  26690. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26691. }
  26692. else {
  26693. var size = {
  26694. width: this.width,
  26695. height: this.height
  26696. };
  26697. proxy = this._engine.createRenderTargetTexture(size, options);
  26698. }
  26699. proxy._swapAndDie(this);
  26700. this.isReady = true;
  26701. return;
  26702. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26703. var depthTextureOptions = {
  26704. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26705. comparisonFunction: this._comparisonFunction,
  26706. generateStencil: this._generateStencilBuffer,
  26707. isCube: this.isCube
  26708. };
  26709. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26710. proxy._swapAndDie(this);
  26711. this.isReady = true;
  26712. return;
  26713. case InternalTexture.DATASOURCE_CUBE:
  26714. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26715. _this.isReady = true;
  26716. }, null, this.format, this._extension);
  26717. proxy._swapAndDie(this);
  26718. return;
  26719. case InternalTexture.DATASOURCE_CUBERAW:
  26720. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26721. proxy._swapAndDie(this);
  26722. this.isReady = true;
  26723. return;
  26724. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26725. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26726. if (proxy) {
  26727. proxy._swapAndDie(_this);
  26728. }
  26729. _this.isReady = true;
  26730. }, null, this.format, this._extension);
  26731. return;
  26732. }
  26733. };
  26734. InternalTexture.prototype._swapAndDie = function (target) {
  26735. target._webGLTexture = this._webGLTexture;
  26736. if (this._framebuffer) {
  26737. target._framebuffer = this._framebuffer;
  26738. }
  26739. if (this._depthStencilBuffer) {
  26740. target._depthStencilBuffer = this._depthStencilBuffer;
  26741. }
  26742. if (this._lodTextureHigh) {
  26743. if (target._lodTextureHigh) {
  26744. target._lodTextureHigh.dispose();
  26745. }
  26746. target._lodTextureHigh = this._lodTextureHigh;
  26747. }
  26748. if (this._lodTextureMid) {
  26749. if (target._lodTextureMid) {
  26750. target._lodTextureMid.dispose();
  26751. }
  26752. target._lodTextureMid = this._lodTextureMid;
  26753. }
  26754. if (this._lodTextureLow) {
  26755. if (target._lodTextureLow) {
  26756. target._lodTextureLow.dispose();
  26757. }
  26758. target._lodTextureLow = this._lodTextureLow;
  26759. }
  26760. var cache = this._engine.getLoadedTexturesCache();
  26761. var index = cache.indexOf(this);
  26762. if (index !== -1) {
  26763. cache.splice(index, 1);
  26764. }
  26765. };
  26766. /**
  26767. * Dispose the current allocated resources
  26768. */
  26769. InternalTexture.prototype.dispose = function () {
  26770. if (!this._webGLTexture) {
  26771. return;
  26772. }
  26773. this._references--;
  26774. if (this._references === 0) {
  26775. this._engine._releaseTexture(this);
  26776. this._webGLTexture = null;
  26777. this.previous = null;
  26778. this.next = null;
  26779. }
  26780. };
  26781. /**
  26782. * The source of the texture data is unknown
  26783. */
  26784. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26785. /**
  26786. * Texture data comes from an URL
  26787. */
  26788. InternalTexture.DATASOURCE_URL = 1;
  26789. /**
  26790. * Texture data is only used for temporary storage
  26791. */
  26792. InternalTexture.DATASOURCE_TEMP = 2;
  26793. /**
  26794. * Texture data comes from raw data (ArrayBuffer)
  26795. */
  26796. InternalTexture.DATASOURCE_RAW = 3;
  26797. /**
  26798. * Texture content is dynamic (video or dynamic texture)
  26799. */
  26800. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26801. /**
  26802. * Texture content is generated by rendering to it
  26803. */
  26804. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26805. /**
  26806. * Texture content is part of a multi render target process
  26807. */
  26808. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26809. /**
  26810. * Texture data comes from a cube data file
  26811. */
  26812. InternalTexture.DATASOURCE_CUBE = 7;
  26813. /**
  26814. * Texture data comes from a raw cube data
  26815. */
  26816. InternalTexture.DATASOURCE_CUBERAW = 8;
  26817. /**
  26818. * Texture data come from a prefiltered cube data file
  26819. */
  26820. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26821. /**
  26822. * Texture content is raw 3D data
  26823. */
  26824. InternalTexture.DATASOURCE_RAW3D = 10;
  26825. /**
  26826. * Texture content is a depth texture
  26827. */
  26828. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26829. return InternalTexture;
  26830. }());
  26831. BABYLON.InternalTexture = InternalTexture;
  26832. })(BABYLON || (BABYLON = {}));
  26833. //# sourceMappingURL=babylon.internalTexture.js.map
  26834. "use strict";
  26835. var BABYLON;
  26836. (function (BABYLON) {
  26837. var BaseTexture = /** @class */ (function () {
  26838. function BaseTexture(scene) {
  26839. this._hasAlpha = false;
  26840. this.getAlphaFromRGB = false;
  26841. this.level = 1;
  26842. this.coordinatesIndex = 0;
  26843. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26844. /**
  26845. * | Value | Type | Description |
  26846. * | ----- | ------------------ | ----------- |
  26847. * | 0 | CLAMP_ADDRESSMODE | |
  26848. * | 1 | WRAP_ADDRESSMODE | |
  26849. * | 2 | MIRROR_ADDRESSMODE | |
  26850. */
  26851. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26852. /**
  26853. * | Value | Type | Description |
  26854. * | ----- | ------------------ | ----------- |
  26855. * | 0 | CLAMP_ADDRESSMODE | |
  26856. * | 1 | WRAP_ADDRESSMODE | |
  26857. * | 2 | MIRROR_ADDRESSMODE | |
  26858. */
  26859. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26860. /**
  26861. * | Value | Type | Description |
  26862. * | ----- | ------------------ | ----------- |
  26863. * | 0 | CLAMP_ADDRESSMODE | |
  26864. * | 1 | WRAP_ADDRESSMODE | |
  26865. * | 2 | MIRROR_ADDRESSMODE | |
  26866. */
  26867. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26868. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26869. this.isCube = false;
  26870. this.is3D = false;
  26871. this.gammaSpace = true;
  26872. this.invertZ = false;
  26873. this.lodLevelInAlpha = false;
  26874. this.lodGenerationOffset = 0.0;
  26875. this.lodGenerationScale = 0.8;
  26876. this.isRenderTarget = false;
  26877. this.animations = new Array();
  26878. /**
  26879. * An event triggered when the texture is disposed.
  26880. * @type {BABYLON.Observable}
  26881. */
  26882. this.onDisposeObservable = new BABYLON.Observable();
  26883. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26884. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26885. if (this._scene) {
  26886. this._scene.textures.push(this);
  26887. }
  26888. this._uid = null;
  26889. }
  26890. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26891. get: function () {
  26892. return this._hasAlpha;
  26893. },
  26894. set: function (value) {
  26895. if (this._hasAlpha === value) {
  26896. return;
  26897. }
  26898. this._hasAlpha = value;
  26899. if (this._scene) {
  26900. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26901. }
  26902. },
  26903. enumerable: true,
  26904. configurable: true
  26905. });
  26906. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26907. get: function () {
  26908. return this._coordinatesMode;
  26909. },
  26910. /**
  26911. * How a texture is mapped.
  26912. *
  26913. * | Value | Type | Description |
  26914. * | ----- | ----------------------------------- | ----------- |
  26915. * | 0 | EXPLICIT_MODE | |
  26916. * | 1 | SPHERICAL_MODE | |
  26917. * | 2 | PLANAR_MODE | |
  26918. * | 3 | CUBIC_MODE | |
  26919. * | 4 | PROJECTION_MODE | |
  26920. * | 5 | SKYBOX_MODE | |
  26921. * | 6 | INVCUBIC_MODE | |
  26922. * | 7 | EQUIRECTANGULAR_MODE | |
  26923. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26924. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26925. */
  26926. set: function (value) {
  26927. if (this._coordinatesMode === value) {
  26928. return;
  26929. }
  26930. this._coordinatesMode = value;
  26931. if (this._scene) {
  26932. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26933. }
  26934. },
  26935. enumerable: true,
  26936. configurable: true
  26937. });
  26938. Object.defineProperty(BaseTexture.prototype, "uid", {
  26939. get: function () {
  26940. if (!this._uid) {
  26941. this._uid = BABYLON.Tools.RandomId();
  26942. }
  26943. return this._uid;
  26944. },
  26945. enumerable: true,
  26946. configurable: true
  26947. });
  26948. BaseTexture.prototype.toString = function () {
  26949. return this.name;
  26950. };
  26951. BaseTexture.prototype.getClassName = function () {
  26952. return "BaseTexture";
  26953. };
  26954. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26955. set: function (callback) {
  26956. if (this._onDisposeObserver) {
  26957. this.onDisposeObservable.remove(this._onDisposeObserver);
  26958. }
  26959. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26960. },
  26961. enumerable: true,
  26962. configurable: true
  26963. });
  26964. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26965. get: function () {
  26966. return true;
  26967. },
  26968. enumerable: true,
  26969. configurable: true
  26970. });
  26971. BaseTexture.prototype.getScene = function () {
  26972. return this._scene;
  26973. };
  26974. BaseTexture.prototype.getTextureMatrix = function () {
  26975. return BABYLON.Matrix.IdentityReadOnly;
  26976. };
  26977. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26978. return BABYLON.Matrix.IdentityReadOnly;
  26979. };
  26980. BaseTexture.prototype.getInternalTexture = function () {
  26981. return this._texture;
  26982. };
  26983. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26984. return !this.isBlocking || this.isReady();
  26985. };
  26986. BaseTexture.prototype.isReady = function () {
  26987. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26988. this.delayLoad();
  26989. return false;
  26990. }
  26991. if (this._texture) {
  26992. return this._texture.isReady;
  26993. }
  26994. return false;
  26995. };
  26996. BaseTexture.prototype.getSize = function () {
  26997. if (this._texture && this._texture.width) {
  26998. return new BABYLON.Size(this._texture.width, this._texture.height);
  26999. }
  27000. if (this._texture && this._texture._size) {
  27001. return new BABYLON.Size(this._texture._size, this._texture._size);
  27002. }
  27003. return BABYLON.Size.Zero();
  27004. };
  27005. BaseTexture.prototype.getBaseSize = function () {
  27006. if (!this.isReady() || !this._texture)
  27007. return BABYLON.Size.Zero();
  27008. if (this._texture._size) {
  27009. return new BABYLON.Size(this._texture._size, this._texture._size);
  27010. }
  27011. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27012. };
  27013. BaseTexture.prototype.scale = function (ratio) {
  27014. };
  27015. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27016. get: function () {
  27017. return false;
  27018. },
  27019. enumerable: true,
  27020. configurable: true
  27021. });
  27022. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27023. if (!this._scene) {
  27024. return null;
  27025. }
  27026. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27027. for (var index = 0; index < texturesCache.length; index++) {
  27028. var texturesCacheEntry = texturesCache[index];
  27029. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27030. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27031. texturesCacheEntry.incrementReferences();
  27032. return texturesCacheEntry;
  27033. }
  27034. }
  27035. }
  27036. return null;
  27037. };
  27038. BaseTexture.prototype._rebuild = function () {
  27039. };
  27040. BaseTexture.prototype.delayLoad = function () {
  27041. };
  27042. BaseTexture.prototype.clone = function () {
  27043. return null;
  27044. };
  27045. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27046. get: function () {
  27047. if (!this._texture) {
  27048. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27049. }
  27050. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27051. },
  27052. enumerable: true,
  27053. configurable: true
  27054. });
  27055. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27056. get: function () {
  27057. if (!this._texture) {
  27058. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27059. }
  27060. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27061. },
  27062. enumerable: true,
  27063. configurable: true
  27064. });
  27065. BaseTexture.prototype.readPixels = function (faceIndex) {
  27066. if (faceIndex === void 0) { faceIndex = 0; }
  27067. if (!this._texture) {
  27068. return null;
  27069. }
  27070. var size = this.getSize();
  27071. var scene = this.getScene();
  27072. if (!scene) {
  27073. return null;
  27074. }
  27075. var engine = scene.getEngine();
  27076. if (this._texture.isCube) {
  27077. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27078. }
  27079. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27080. };
  27081. BaseTexture.prototype.releaseInternalTexture = function () {
  27082. if (this._texture) {
  27083. this._texture.dispose();
  27084. this._texture = null;
  27085. }
  27086. };
  27087. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27088. get: function () {
  27089. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27090. return null;
  27091. }
  27092. if (!this._texture._sphericalPolynomial) {
  27093. this._texture._sphericalPolynomial =
  27094. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27095. }
  27096. return this._texture._sphericalPolynomial;
  27097. },
  27098. set: function (value) {
  27099. if (this._texture) {
  27100. this._texture._sphericalPolynomial = value;
  27101. }
  27102. },
  27103. enumerable: true,
  27104. configurable: true
  27105. });
  27106. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27107. get: function () {
  27108. if (this._texture) {
  27109. return this._texture._lodTextureHigh;
  27110. }
  27111. return null;
  27112. },
  27113. enumerable: true,
  27114. configurable: true
  27115. });
  27116. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27117. get: function () {
  27118. if (this._texture) {
  27119. return this._texture._lodTextureMid;
  27120. }
  27121. return null;
  27122. },
  27123. enumerable: true,
  27124. configurable: true
  27125. });
  27126. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27127. get: function () {
  27128. if (this._texture) {
  27129. return this._texture._lodTextureLow;
  27130. }
  27131. return null;
  27132. },
  27133. enumerable: true,
  27134. configurable: true
  27135. });
  27136. BaseTexture.prototype.dispose = function () {
  27137. if (!this._scene) {
  27138. return;
  27139. }
  27140. // Animations
  27141. this._scene.stopAnimation(this);
  27142. // Remove from scene
  27143. this._scene._removePendingData(this);
  27144. var index = this._scene.textures.indexOf(this);
  27145. if (index >= 0) {
  27146. this._scene.textures.splice(index, 1);
  27147. }
  27148. if (this._texture === undefined) {
  27149. return;
  27150. }
  27151. // Release
  27152. this.releaseInternalTexture();
  27153. // Callback
  27154. this.onDisposeObservable.notifyObservers(this);
  27155. this.onDisposeObservable.clear();
  27156. };
  27157. BaseTexture.prototype.serialize = function () {
  27158. if (!this.name) {
  27159. return null;
  27160. }
  27161. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27162. // Animations
  27163. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27164. return serializationObject;
  27165. };
  27166. BaseTexture.WhenAllReady = function (textures, callback) {
  27167. var numRemaining = textures.length;
  27168. if (numRemaining === 0) {
  27169. callback();
  27170. return;
  27171. }
  27172. var _loop_1 = function () {
  27173. texture = textures[i];
  27174. if (texture.isReady()) {
  27175. if (--numRemaining === 0) {
  27176. callback();
  27177. }
  27178. }
  27179. else {
  27180. onLoadObservable = texture.onLoadObservable;
  27181. var onLoadCallback_1 = function () {
  27182. onLoadObservable.removeCallback(onLoadCallback_1);
  27183. if (--numRemaining === 0) {
  27184. callback();
  27185. }
  27186. };
  27187. onLoadObservable.add(onLoadCallback_1);
  27188. }
  27189. };
  27190. var texture, onLoadObservable;
  27191. for (var i = 0; i < textures.length; i++) {
  27192. _loop_1();
  27193. }
  27194. };
  27195. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27196. __decorate([
  27197. BABYLON.serialize()
  27198. ], BaseTexture.prototype, "name", void 0);
  27199. __decorate([
  27200. BABYLON.serialize("hasAlpha")
  27201. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27202. __decorate([
  27203. BABYLON.serialize()
  27204. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27205. __decorate([
  27206. BABYLON.serialize()
  27207. ], BaseTexture.prototype, "level", void 0);
  27208. __decorate([
  27209. BABYLON.serialize()
  27210. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27211. __decorate([
  27212. BABYLON.serialize("coordinatesMode")
  27213. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27214. __decorate([
  27215. BABYLON.serialize()
  27216. ], BaseTexture.prototype, "wrapU", void 0);
  27217. __decorate([
  27218. BABYLON.serialize()
  27219. ], BaseTexture.prototype, "wrapV", void 0);
  27220. __decorate([
  27221. BABYLON.serialize()
  27222. ], BaseTexture.prototype, "wrapR", void 0);
  27223. __decorate([
  27224. BABYLON.serialize()
  27225. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27226. __decorate([
  27227. BABYLON.serialize()
  27228. ], BaseTexture.prototype, "isCube", void 0);
  27229. __decorate([
  27230. BABYLON.serialize()
  27231. ], BaseTexture.prototype, "is3D", void 0);
  27232. __decorate([
  27233. BABYLON.serialize()
  27234. ], BaseTexture.prototype, "gammaSpace", void 0);
  27235. __decorate([
  27236. BABYLON.serialize()
  27237. ], BaseTexture.prototype, "invertZ", void 0);
  27238. __decorate([
  27239. BABYLON.serialize()
  27240. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27241. __decorate([
  27242. BABYLON.serialize()
  27243. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27244. __decorate([
  27245. BABYLON.serialize()
  27246. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27247. __decorate([
  27248. BABYLON.serialize()
  27249. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27250. return BaseTexture;
  27251. }());
  27252. BABYLON.BaseTexture = BaseTexture;
  27253. })(BABYLON || (BABYLON = {}));
  27254. //# sourceMappingURL=babylon.baseTexture.js.map
  27255. "use strict";
  27256. var BABYLON;
  27257. (function (BABYLON) {
  27258. var Texture = /** @class */ (function (_super) {
  27259. __extends(Texture, _super);
  27260. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27261. if (noMipmap === void 0) { noMipmap = false; }
  27262. if (invertY === void 0) { invertY = true; }
  27263. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27264. if (onLoad === void 0) { onLoad = null; }
  27265. if (onError === void 0) { onError = null; }
  27266. if (buffer === void 0) { buffer = null; }
  27267. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27268. var _this = _super.call(this, scene) || this;
  27269. _this.uOffset = 0;
  27270. _this.vOffset = 0;
  27271. _this.uScale = 1.0;
  27272. _this.vScale = 1.0;
  27273. _this.uAng = 0;
  27274. _this.vAng = 0;
  27275. _this.wAng = 0;
  27276. _this._isBlocking = true;
  27277. _this.name = url || "";
  27278. _this.url = url;
  27279. _this._noMipmap = noMipmap;
  27280. _this._invertY = invertY;
  27281. _this._samplingMode = samplingMode;
  27282. _this._buffer = buffer;
  27283. _this._deleteBuffer = deleteBuffer;
  27284. if (format) {
  27285. _this._format = format;
  27286. }
  27287. scene = _this.getScene();
  27288. if (!scene) {
  27289. return _this;
  27290. }
  27291. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27292. var load = function () {
  27293. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27294. _this.onLoadObservable.notifyObservers(_this);
  27295. }
  27296. if (onLoad) {
  27297. onLoad();
  27298. }
  27299. if (!_this.isBlocking && scene) {
  27300. scene.resetCachedMaterial();
  27301. }
  27302. };
  27303. if (!_this.url) {
  27304. _this._delayedOnLoad = load;
  27305. _this._delayedOnError = onError;
  27306. return _this;
  27307. }
  27308. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27309. if (!_this._texture) {
  27310. if (!scene.useDelayedTextureLoading) {
  27311. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27312. if (deleteBuffer) {
  27313. delete _this._buffer;
  27314. }
  27315. }
  27316. else {
  27317. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27318. _this._delayedOnLoad = load;
  27319. _this._delayedOnError = onError;
  27320. }
  27321. }
  27322. else {
  27323. if (_this._texture.isReady) {
  27324. BABYLON.Tools.SetImmediate(function () { return load(); });
  27325. }
  27326. else {
  27327. _this._texture.onLoadedObservable.add(load);
  27328. }
  27329. }
  27330. return _this;
  27331. }
  27332. Object.defineProperty(Texture.prototype, "noMipmap", {
  27333. get: function () {
  27334. return this._noMipmap;
  27335. },
  27336. enumerable: true,
  27337. configurable: true
  27338. });
  27339. Object.defineProperty(Texture.prototype, "isBlocking", {
  27340. get: function () {
  27341. return this._isBlocking;
  27342. },
  27343. set: function (value) {
  27344. this._isBlocking = value;
  27345. },
  27346. enumerable: true,
  27347. configurable: true
  27348. });
  27349. Object.defineProperty(Texture.prototype, "samplingMode", {
  27350. get: function () {
  27351. return this._samplingMode;
  27352. },
  27353. enumerable: true,
  27354. configurable: true
  27355. });
  27356. Texture.prototype.updateURL = function (url) {
  27357. this.url = url;
  27358. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27359. this.delayLoad();
  27360. };
  27361. Texture.prototype.delayLoad = function () {
  27362. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27363. return;
  27364. }
  27365. var scene = this.getScene();
  27366. if (!scene) {
  27367. return;
  27368. }
  27369. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27370. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27371. if (!this._texture) {
  27372. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27373. if (this._deleteBuffer) {
  27374. delete this._buffer;
  27375. }
  27376. }
  27377. else {
  27378. if (this._delayedOnLoad) {
  27379. if (this._texture.isReady) {
  27380. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27381. }
  27382. else {
  27383. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27384. }
  27385. }
  27386. }
  27387. this._delayedOnLoad = null;
  27388. this._delayedOnError = null;
  27389. };
  27390. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27391. if (!this._texture) {
  27392. return;
  27393. }
  27394. var scene = this.getScene();
  27395. if (!scene) {
  27396. return;
  27397. }
  27398. this._samplingMode = samplingMode;
  27399. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27400. };
  27401. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27402. x *= this.uScale;
  27403. y *= this.vScale;
  27404. x -= 0.5 * this.uScale;
  27405. y -= 0.5 * this.vScale;
  27406. z -= 0.5;
  27407. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27408. t.x += 0.5 * this.uScale + this.uOffset;
  27409. t.y += 0.5 * this.vScale + this.vOffset;
  27410. t.z += 0.5;
  27411. };
  27412. Texture.prototype.getTextureMatrix = function () {
  27413. var _this = this;
  27414. if (this.uOffset === this._cachedUOffset &&
  27415. this.vOffset === this._cachedVOffset &&
  27416. this.uScale === this._cachedUScale &&
  27417. this.vScale === this._cachedVScale &&
  27418. this.uAng === this._cachedUAng &&
  27419. this.vAng === this._cachedVAng &&
  27420. this.wAng === this._cachedWAng) {
  27421. return this._cachedTextureMatrix;
  27422. }
  27423. this._cachedUOffset = this.uOffset;
  27424. this._cachedVOffset = this.vOffset;
  27425. this._cachedUScale = this.uScale;
  27426. this._cachedVScale = this.vScale;
  27427. this._cachedUAng = this.uAng;
  27428. this._cachedVAng = this.vAng;
  27429. this._cachedWAng = this.wAng;
  27430. if (!this._cachedTextureMatrix) {
  27431. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27432. this._rowGenerationMatrix = new BABYLON.Matrix();
  27433. this._t0 = BABYLON.Vector3.Zero();
  27434. this._t1 = BABYLON.Vector3.Zero();
  27435. this._t2 = BABYLON.Vector3.Zero();
  27436. }
  27437. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27438. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27439. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27440. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27441. this._t1.subtractInPlace(this._t0);
  27442. this._t2.subtractInPlace(this._t0);
  27443. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27444. this._cachedTextureMatrix.m[0] = this._t1.x;
  27445. this._cachedTextureMatrix.m[1] = this._t1.y;
  27446. this._cachedTextureMatrix.m[2] = this._t1.z;
  27447. this._cachedTextureMatrix.m[4] = this._t2.x;
  27448. this._cachedTextureMatrix.m[5] = this._t2.y;
  27449. this._cachedTextureMatrix.m[6] = this._t2.z;
  27450. this._cachedTextureMatrix.m[8] = this._t0.x;
  27451. this._cachedTextureMatrix.m[9] = this._t0.y;
  27452. this._cachedTextureMatrix.m[10] = this._t0.z;
  27453. var scene = this.getScene();
  27454. if (!scene) {
  27455. return this._cachedTextureMatrix;
  27456. }
  27457. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27458. return mat.hasTexture(_this);
  27459. });
  27460. return this._cachedTextureMatrix;
  27461. };
  27462. Texture.prototype.getReflectionTextureMatrix = function () {
  27463. var _this = this;
  27464. var scene = this.getScene();
  27465. if (!scene) {
  27466. return this._cachedTextureMatrix;
  27467. }
  27468. if (this.uOffset === this._cachedUOffset &&
  27469. this.vOffset === this._cachedVOffset &&
  27470. this.uScale === this._cachedUScale &&
  27471. this.vScale === this._cachedVScale &&
  27472. this.coordinatesMode === this._cachedCoordinatesMode) {
  27473. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27474. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27475. return this._cachedTextureMatrix;
  27476. }
  27477. }
  27478. else {
  27479. return this._cachedTextureMatrix;
  27480. }
  27481. }
  27482. if (!this._cachedTextureMatrix) {
  27483. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27484. }
  27485. if (!this._projectionModeMatrix) {
  27486. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27487. }
  27488. this._cachedUOffset = this.uOffset;
  27489. this._cachedVOffset = this.vOffset;
  27490. this._cachedUScale = this.uScale;
  27491. this._cachedVScale = this.vScale;
  27492. this._cachedCoordinatesMode = this.coordinatesMode;
  27493. switch (this.coordinatesMode) {
  27494. case Texture.PLANAR_MODE:
  27495. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27496. this._cachedTextureMatrix[0] = this.uScale;
  27497. this._cachedTextureMatrix[5] = this.vScale;
  27498. this._cachedTextureMatrix[12] = this.uOffset;
  27499. this._cachedTextureMatrix[13] = this.vOffset;
  27500. break;
  27501. case Texture.PROJECTION_MODE:
  27502. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27503. this._projectionModeMatrix.m[0] = 0.5;
  27504. this._projectionModeMatrix.m[5] = -0.5;
  27505. this._projectionModeMatrix.m[10] = 0.0;
  27506. this._projectionModeMatrix.m[12] = 0.5;
  27507. this._projectionModeMatrix.m[13] = 0.5;
  27508. this._projectionModeMatrix.m[14] = 1.0;
  27509. this._projectionModeMatrix.m[15] = 1.0;
  27510. var projectionMatrix = scene.getProjectionMatrix();
  27511. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27512. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27513. break;
  27514. default:
  27515. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27516. break;
  27517. }
  27518. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27519. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27520. });
  27521. return this._cachedTextureMatrix;
  27522. };
  27523. Texture.prototype.clone = function () {
  27524. var _this = this;
  27525. return BABYLON.SerializationHelper.Clone(function () {
  27526. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27527. }, this);
  27528. };
  27529. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27530. get: function () {
  27531. if (!this._onLoadObservable) {
  27532. this._onLoadObservable = new BABYLON.Observable();
  27533. }
  27534. return this._onLoadObservable;
  27535. },
  27536. enumerable: true,
  27537. configurable: true
  27538. });
  27539. Texture.prototype.serialize = function () {
  27540. var serializationObject = _super.prototype.serialize.call(this);
  27541. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27542. serializationObject.base64String = this._buffer;
  27543. serializationObject.name = serializationObject.name.replace("data:", "");
  27544. }
  27545. return serializationObject;
  27546. };
  27547. Texture.prototype.getClassName = function () {
  27548. return "Texture";
  27549. };
  27550. Texture.prototype.dispose = function () {
  27551. _super.prototype.dispose.call(this);
  27552. if (this.onLoadObservable) {
  27553. this.onLoadObservable.clear();
  27554. this._onLoadObservable = null;
  27555. }
  27556. this._delayedOnLoad = null;
  27557. this._delayedOnError = null;
  27558. };
  27559. // Statics
  27560. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27561. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27562. if (onLoad === void 0) { onLoad = null; }
  27563. if (onError === void 0) { onError = null; }
  27564. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27565. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27566. };
  27567. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27568. if (parsedTexture.customType) {
  27569. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27570. // Update Sampling Mode
  27571. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27572. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27573. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27574. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27575. }
  27576. }
  27577. return parsedCustomTexture;
  27578. }
  27579. if (parsedTexture.isCube) {
  27580. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27581. }
  27582. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27583. return null;
  27584. }
  27585. var texture = BABYLON.SerializationHelper.Parse(function () {
  27586. var generateMipMaps = true;
  27587. if (parsedTexture.noMipmap) {
  27588. generateMipMaps = false;
  27589. }
  27590. if (parsedTexture.mirrorPlane) {
  27591. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27592. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27593. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27594. return mirrorTexture;
  27595. }
  27596. else if (parsedTexture.isRenderTarget) {
  27597. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27598. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27599. return renderTargetTexture;
  27600. }
  27601. else {
  27602. var texture;
  27603. if (parsedTexture.base64String) {
  27604. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27605. }
  27606. else {
  27607. var url = rootUrl + parsedTexture.name;
  27608. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27609. url = parsedTexture.url;
  27610. }
  27611. texture = new Texture(url, scene, !generateMipMaps);
  27612. }
  27613. return texture;
  27614. }
  27615. }, parsedTexture, scene);
  27616. // Update Sampling Mode
  27617. if (parsedTexture.samplingMode) {
  27618. var sampling = parsedTexture.samplingMode;
  27619. if (texture._samplingMode !== sampling) {
  27620. texture.updateSamplingMode(sampling);
  27621. }
  27622. }
  27623. // Animations
  27624. if (parsedTexture.animations) {
  27625. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27626. var parsedAnimation = parsedTexture.animations[animationIndex];
  27627. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27628. }
  27629. }
  27630. return texture;
  27631. };
  27632. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27633. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27634. if (noMipmap === void 0) { noMipmap = false; }
  27635. if (invertY === void 0) { invertY = true; }
  27636. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27637. if (onLoad === void 0) { onLoad = null; }
  27638. if (onError === void 0) { onError = null; }
  27639. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27640. if (name.substr(0, 5) !== "data:") {
  27641. name = "data:" + name;
  27642. }
  27643. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27644. };
  27645. // Constants
  27646. Texture.NEAREST_SAMPLINGMODE = 1;
  27647. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27648. Texture.BILINEAR_SAMPLINGMODE = 2;
  27649. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27650. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27651. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27652. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27653. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27654. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27655. Texture.NEAREST_LINEAR = 7;
  27656. Texture.NEAREST_NEAREST = 8;
  27657. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27658. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27659. Texture.LINEAR_LINEAR = 11;
  27660. Texture.LINEAR_NEAREST = 12;
  27661. Texture.EXPLICIT_MODE = 0;
  27662. Texture.SPHERICAL_MODE = 1;
  27663. Texture.PLANAR_MODE = 2;
  27664. Texture.CUBIC_MODE = 3;
  27665. Texture.PROJECTION_MODE = 4;
  27666. Texture.SKYBOX_MODE = 5;
  27667. Texture.INVCUBIC_MODE = 6;
  27668. Texture.EQUIRECTANGULAR_MODE = 7;
  27669. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27670. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27671. Texture.CLAMP_ADDRESSMODE = 0;
  27672. Texture.WRAP_ADDRESSMODE = 1;
  27673. Texture.MIRROR_ADDRESSMODE = 2;
  27674. /**
  27675. * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
  27676. */
  27677. Texture.UseSerializedUrlIfAny = false;
  27678. __decorate([
  27679. BABYLON.serialize()
  27680. ], Texture.prototype, "url", void 0);
  27681. __decorate([
  27682. BABYLON.serialize()
  27683. ], Texture.prototype, "uOffset", void 0);
  27684. __decorate([
  27685. BABYLON.serialize()
  27686. ], Texture.prototype, "vOffset", void 0);
  27687. __decorate([
  27688. BABYLON.serialize()
  27689. ], Texture.prototype, "uScale", void 0);
  27690. __decorate([
  27691. BABYLON.serialize()
  27692. ], Texture.prototype, "vScale", void 0);
  27693. __decorate([
  27694. BABYLON.serialize()
  27695. ], Texture.prototype, "uAng", void 0);
  27696. __decorate([
  27697. BABYLON.serialize()
  27698. ], Texture.prototype, "vAng", void 0);
  27699. __decorate([
  27700. BABYLON.serialize()
  27701. ], Texture.prototype, "wAng", void 0);
  27702. __decorate([
  27703. BABYLON.serialize()
  27704. ], Texture.prototype, "isBlocking", null);
  27705. return Texture;
  27706. }(BABYLON.BaseTexture));
  27707. BABYLON.Texture = Texture;
  27708. })(BABYLON || (BABYLON = {}));
  27709. //# sourceMappingURL=babylon.texture.js.map
  27710. "use strict";
  27711. var BABYLON;
  27712. (function (BABYLON) {
  27713. var _InstancesBatch = /** @class */ (function () {
  27714. function _InstancesBatch() {
  27715. this.mustReturn = false;
  27716. this.visibleInstances = new Array();
  27717. this.renderSelf = new Array();
  27718. }
  27719. return _InstancesBatch;
  27720. }());
  27721. BABYLON._InstancesBatch = _InstancesBatch;
  27722. var Mesh = /** @class */ (function (_super) {
  27723. __extends(Mesh, _super);
  27724. /**
  27725. * @constructor
  27726. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27727. * @param {Scene} scene The scene to add this mesh to.
  27728. * @param {Node} parent The parent of this mesh, if it has one
  27729. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27730. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27731. * When false, achieved by calling a clone(), also passing False.
  27732. * This will make creation of children, recursive.
  27733. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27734. */
  27735. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27736. if (scene === void 0) { scene = null; }
  27737. if (parent === void 0) { parent = null; }
  27738. if (source === void 0) { source = null; }
  27739. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27740. var _this = _super.call(this, name, scene) || this;
  27741. // Events
  27742. /**
  27743. * An event triggered before rendering the mesh
  27744. * @type {BABYLON.Observable}
  27745. */
  27746. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27747. /**
  27748. * An event triggered after rendering the mesh
  27749. * @type {BABYLON.Observable}
  27750. */
  27751. _this.onAfterRenderObservable = new BABYLON.Observable();
  27752. /**
  27753. * An event triggered before drawing the mesh
  27754. * @type {BABYLON.Observable}
  27755. */
  27756. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27757. // Members
  27758. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27759. _this.instances = new Array();
  27760. _this._LODLevels = new Array();
  27761. _this._visibleInstances = {};
  27762. _this._renderIdForInstances = new Array();
  27763. _this._batchCache = new _InstancesBatch();
  27764. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27765. // Use by builder only to know what orientation were the mesh build in.
  27766. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27767. _this.overrideMaterialSideOrientation = null;
  27768. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27769. // Will be used to save a source mesh reference, If any
  27770. _this._source = null;
  27771. scene = _this.getScene();
  27772. if (source) {
  27773. // Source mesh
  27774. _this._source = source;
  27775. // Geometry
  27776. if (source._geometry) {
  27777. source._geometry.applyToMesh(_this);
  27778. }
  27779. // Deep copy
  27780. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27781. // Metadata
  27782. if (source.metadata && source.metadata.clone) {
  27783. _this.metadata = source.metadata.clone();
  27784. }
  27785. else {
  27786. _this.metadata = source.metadata;
  27787. }
  27788. // Tags
  27789. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27790. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27791. }
  27792. // Parent
  27793. _this.parent = source.parent;
  27794. // Pivot
  27795. _this.setPivotMatrix(source.getPivotMatrix());
  27796. _this.id = name + "." + source.id;
  27797. // Material
  27798. _this.material = source.material;
  27799. var index;
  27800. if (!doNotCloneChildren) {
  27801. // Children
  27802. var directDescendants = source.getDescendants(true);
  27803. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27804. var child = directDescendants[index_1];
  27805. if (child.clone) {
  27806. child.clone(name + "." + child.name, _this);
  27807. }
  27808. }
  27809. }
  27810. // Physics clone
  27811. var physicsEngine = _this.getScene().getPhysicsEngine();
  27812. if (clonePhysicsImpostor && physicsEngine) {
  27813. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27814. if (impostor) {
  27815. _this.physicsImpostor = impostor.clone(_this);
  27816. }
  27817. }
  27818. // Particles
  27819. for (index = 0; index < scene.particleSystems.length; index++) {
  27820. var system = scene.particleSystems[index];
  27821. if (system.emitter === source) {
  27822. system.clone(system.name, _this);
  27823. }
  27824. }
  27825. _this.computeWorldMatrix(true);
  27826. }
  27827. // Parent
  27828. if (parent !== null) {
  27829. _this.parent = parent;
  27830. }
  27831. return _this;
  27832. }
  27833. Object.defineProperty(Mesh, "FRONTSIDE", {
  27834. /**
  27835. * Mesh side orientation : usually the external or front surface
  27836. */
  27837. get: function () {
  27838. return Mesh._FRONTSIDE;
  27839. },
  27840. enumerable: true,
  27841. configurable: true
  27842. });
  27843. Object.defineProperty(Mesh, "BACKSIDE", {
  27844. /**
  27845. * Mesh side orientation : usually the internal or back surface
  27846. */
  27847. get: function () {
  27848. return Mesh._BACKSIDE;
  27849. },
  27850. enumerable: true,
  27851. configurable: true
  27852. });
  27853. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27854. /**
  27855. * Mesh side orientation : both internal and external or front and back surfaces
  27856. */
  27857. get: function () {
  27858. return Mesh._DOUBLESIDE;
  27859. },
  27860. enumerable: true,
  27861. configurable: true
  27862. });
  27863. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27864. /**
  27865. * Mesh side orientation : by default, `FRONTSIDE`
  27866. */
  27867. get: function () {
  27868. return Mesh._DEFAULTSIDE;
  27869. },
  27870. enumerable: true,
  27871. configurable: true
  27872. });
  27873. Object.defineProperty(Mesh, "NO_CAP", {
  27874. /**
  27875. * Mesh cap setting : no cap
  27876. */
  27877. get: function () {
  27878. return Mesh._NO_CAP;
  27879. },
  27880. enumerable: true,
  27881. configurable: true
  27882. });
  27883. Object.defineProperty(Mesh, "CAP_START", {
  27884. /**
  27885. * Mesh cap setting : one cap at the beginning of the mesh
  27886. */
  27887. get: function () {
  27888. return Mesh._CAP_START;
  27889. },
  27890. enumerable: true,
  27891. configurable: true
  27892. });
  27893. Object.defineProperty(Mesh, "CAP_END", {
  27894. /**
  27895. * Mesh cap setting : one cap at the end of the mesh
  27896. */
  27897. get: function () {
  27898. return Mesh._CAP_END;
  27899. },
  27900. enumerable: true,
  27901. configurable: true
  27902. });
  27903. Object.defineProperty(Mesh, "CAP_ALL", {
  27904. /**
  27905. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27906. */
  27907. get: function () {
  27908. return Mesh._CAP_ALL;
  27909. },
  27910. enumerable: true,
  27911. configurable: true
  27912. });
  27913. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27914. set: function (callback) {
  27915. if (this._onBeforeDrawObserver) {
  27916. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27917. }
  27918. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27919. },
  27920. enumerable: true,
  27921. configurable: true
  27922. });
  27923. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27924. get: function () {
  27925. return this._morphTargetManager;
  27926. },
  27927. set: function (value) {
  27928. if (this._morphTargetManager === value) {
  27929. return;
  27930. }
  27931. this._morphTargetManager = value;
  27932. this._syncGeometryWithMorphTargetManager();
  27933. },
  27934. enumerable: true,
  27935. configurable: true
  27936. });
  27937. Object.defineProperty(Mesh.prototype, "source", {
  27938. get: function () {
  27939. return this._source;
  27940. },
  27941. enumerable: true,
  27942. configurable: true
  27943. });
  27944. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27945. get: function () {
  27946. return this._unIndexed;
  27947. },
  27948. set: function (value) {
  27949. if (this._unIndexed !== value) {
  27950. this._unIndexed = value;
  27951. this._markSubMeshesAsAttributesDirty();
  27952. }
  27953. },
  27954. enumerable: true,
  27955. configurable: true
  27956. });
  27957. // Methods
  27958. /**
  27959. * Returns the string "Mesh".
  27960. */
  27961. Mesh.prototype.getClassName = function () {
  27962. return "Mesh";
  27963. };
  27964. /**
  27965. * Returns a string.
  27966. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27967. */
  27968. Mesh.prototype.toString = function (fullDetails) {
  27969. var ret = _super.prototype.toString.call(this, fullDetails);
  27970. ret += ", n vertices: " + this.getTotalVertices();
  27971. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27972. if (this.animations) {
  27973. for (var i = 0; i < this.animations.length; i++) {
  27974. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27975. }
  27976. }
  27977. if (fullDetails) {
  27978. if (this._geometry) {
  27979. var ib = this.getIndices();
  27980. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27981. if (vb && ib) {
  27982. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27983. }
  27984. }
  27985. else {
  27986. ret += ", flat shading: UNKNOWN";
  27987. }
  27988. }
  27989. return ret;
  27990. };
  27991. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27992. /**
  27993. * True if the mesh has some Levels Of Details (LOD).
  27994. * Returns a boolean.
  27995. */
  27996. get: function () {
  27997. return this._LODLevels.length > 0;
  27998. },
  27999. enumerable: true,
  28000. configurable: true
  28001. });
  28002. /**
  28003. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28004. * @returns an array of {BABYLON.MeshLODLevel}
  28005. */
  28006. Mesh.prototype.getLODLevels = function () {
  28007. return this._LODLevels;
  28008. };
  28009. Mesh.prototype._sortLODLevels = function () {
  28010. this._LODLevels.sort(function (a, b) {
  28011. if (a.distance < b.distance) {
  28012. return 1;
  28013. }
  28014. if (a.distance > b.distance) {
  28015. return -1;
  28016. }
  28017. return 0;
  28018. });
  28019. };
  28020. /**
  28021. * Add a mesh as LOD level triggered at the given distance.
  28022. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28023. * @param {number} distance The distance from the center of the object to show this level
  28024. * @param {Mesh} mesh The mesh to be added as LOD level
  28025. * @return {Mesh} This mesh (for chaining)
  28026. */
  28027. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28028. if (mesh && mesh._masterMesh) {
  28029. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28030. return this;
  28031. }
  28032. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28033. this._LODLevels.push(level);
  28034. if (mesh) {
  28035. mesh._masterMesh = this;
  28036. }
  28037. this._sortLODLevels();
  28038. return this;
  28039. };
  28040. /**
  28041. * Returns the LOD level mesh at the passed distance or null if not found.
  28042. * It is related to the method `addLODLevel(distance, mesh)`.
  28043. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28044. * Returns an object Mesh or `null`.
  28045. */
  28046. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28047. for (var index = 0; index < this._LODLevels.length; index++) {
  28048. var level = this._LODLevels[index];
  28049. if (level.distance === distance) {
  28050. return level.mesh;
  28051. }
  28052. }
  28053. return null;
  28054. };
  28055. /**
  28056. * Remove a mesh from the LOD array
  28057. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28058. * @param {Mesh} mesh The mesh to be removed.
  28059. * @return {Mesh} This mesh (for chaining)
  28060. */
  28061. Mesh.prototype.removeLODLevel = function (mesh) {
  28062. for (var index = 0; index < this._LODLevels.length; index++) {
  28063. if (this._LODLevels[index].mesh === mesh) {
  28064. this._LODLevels.splice(index, 1);
  28065. if (mesh) {
  28066. mesh._masterMesh = null;
  28067. }
  28068. }
  28069. }
  28070. this._sortLODLevels();
  28071. return this;
  28072. };
  28073. /**
  28074. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28075. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28076. */
  28077. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28078. if (!this._LODLevels || this._LODLevels.length === 0) {
  28079. return this;
  28080. }
  28081. var bSphere;
  28082. if (boundingSphere) {
  28083. bSphere = boundingSphere;
  28084. }
  28085. else {
  28086. var boundingInfo = this.getBoundingInfo();
  28087. bSphere = boundingInfo.boundingSphere;
  28088. }
  28089. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28090. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28091. if (this.onLODLevelSelection) {
  28092. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28093. }
  28094. return this;
  28095. }
  28096. for (var index = 0; index < this._LODLevels.length; index++) {
  28097. var level = this._LODLevels[index];
  28098. if (level.distance < distanceToCamera) {
  28099. if (level.mesh) {
  28100. level.mesh._preActivate();
  28101. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28102. }
  28103. if (this.onLODLevelSelection) {
  28104. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28105. }
  28106. return level.mesh;
  28107. }
  28108. }
  28109. if (this.onLODLevelSelection) {
  28110. this.onLODLevelSelection(distanceToCamera, this, this);
  28111. }
  28112. return this;
  28113. };
  28114. Object.defineProperty(Mesh.prototype, "geometry", {
  28115. /**
  28116. * Returns the mesh internal Geometry object.
  28117. */
  28118. get: function () {
  28119. return this._geometry;
  28120. },
  28121. enumerable: true,
  28122. configurable: true
  28123. });
  28124. /**
  28125. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28126. */
  28127. Mesh.prototype.getTotalVertices = function () {
  28128. if (this._geometry === null || this._geometry === undefined) {
  28129. return 0;
  28130. }
  28131. return this._geometry.getTotalVertices();
  28132. };
  28133. /**
  28134. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28135. * 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.
  28136. * You can force the copy with forceCopy === true
  28137. * Returns null if the mesh has no geometry or no vertex buffer.
  28138. * Possible `kind` values :
  28139. * - BABYLON.VertexBuffer.PositionKind
  28140. * - BABYLON.VertexBuffer.UVKind
  28141. * - BABYLON.VertexBuffer.UV2Kind
  28142. * - BABYLON.VertexBuffer.UV3Kind
  28143. * - BABYLON.VertexBuffer.UV4Kind
  28144. * - BABYLON.VertexBuffer.UV5Kind
  28145. * - BABYLON.VertexBuffer.UV6Kind
  28146. * - BABYLON.VertexBuffer.ColorKind
  28147. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28148. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28149. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28150. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28151. */
  28152. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28153. if (!this._geometry) {
  28154. return null;
  28155. }
  28156. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28157. };
  28158. /**
  28159. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28160. * Returns `null` if the mesh has no geometry.
  28161. * Possible `kind` values :
  28162. * - BABYLON.VertexBuffer.PositionKind
  28163. * - BABYLON.VertexBuffer.UVKind
  28164. * - BABYLON.VertexBuffer.UV2Kind
  28165. * - BABYLON.VertexBuffer.UV3Kind
  28166. * - BABYLON.VertexBuffer.UV4Kind
  28167. * - BABYLON.VertexBuffer.UV5Kind
  28168. * - BABYLON.VertexBuffer.UV6Kind
  28169. * - BABYLON.VertexBuffer.ColorKind
  28170. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28171. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28172. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28173. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28174. */
  28175. Mesh.prototype.getVertexBuffer = function (kind) {
  28176. if (!this._geometry) {
  28177. return null;
  28178. }
  28179. return this._geometry.getVertexBuffer(kind);
  28180. };
  28181. /**
  28182. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28183. * Possible `kind` values :
  28184. * - BABYLON.VertexBuffer.PositionKind
  28185. * - BABYLON.VertexBuffer.UVKind
  28186. * - BABYLON.VertexBuffer.UV2Kind
  28187. * - BABYLON.VertexBuffer.UV3Kind
  28188. * - BABYLON.VertexBuffer.UV4Kind
  28189. * - BABYLON.VertexBuffer.UV5Kind
  28190. * - BABYLON.VertexBuffer.UV6Kind
  28191. * - BABYLON.VertexBuffer.ColorKind
  28192. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28193. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28194. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28195. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28196. */
  28197. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28198. if (!this._geometry) {
  28199. if (this._delayInfo) {
  28200. return this._delayInfo.indexOf(kind) !== -1;
  28201. }
  28202. return false;
  28203. }
  28204. return this._geometry.isVerticesDataPresent(kind);
  28205. };
  28206. /**
  28207. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28208. * Possible `kind` values :
  28209. * - BABYLON.VertexBuffer.PositionKind
  28210. * - BABYLON.VertexBuffer.UVKind
  28211. * - BABYLON.VertexBuffer.UV2Kind
  28212. * - BABYLON.VertexBuffer.UV3Kind
  28213. * - BABYLON.VertexBuffer.UV4Kind
  28214. * - BABYLON.VertexBuffer.UV5Kind
  28215. * - BABYLON.VertexBuffer.UV6Kind
  28216. * - BABYLON.VertexBuffer.ColorKind
  28217. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28218. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28219. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28220. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28221. */
  28222. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28223. if (!this._geometry) {
  28224. if (this._delayInfo) {
  28225. return this._delayInfo.indexOf(kind) !== -1;
  28226. }
  28227. return false;
  28228. }
  28229. return this._geometry.isVertexBufferUpdatable(kind);
  28230. };
  28231. /**
  28232. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28233. * Possible `kind` values :
  28234. * - BABYLON.VertexBuffer.PositionKind
  28235. * - BABYLON.VertexBuffer.UVKind
  28236. * - BABYLON.VertexBuffer.UV2Kind
  28237. * - BABYLON.VertexBuffer.UV3Kind
  28238. * - BABYLON.VertexBuffer.UV4Kind
  28239. * - BABYLON.VertexBuffer.UV5Kind
  28240. * - BABYLON.VertexBuffer.UV6Kind
  28241. * - BABYLON.VertexBuffer.ColorKind
  28242. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28243. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28244. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28245. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28246. */
  28247. Mesh.prototype.getVerticesDataKinds = function () {
  28248. if (!this._geometry) {
  28249. var result = new Array();
  28250. if (this._delayInfo) {
  28251. this._delayInfo.forEach(function (kind, index, array) {
  28252. result.push(kind);
  28253. });
  28254. }
  28255. return result;
  28256. }
  28257. return this._geometry.getVerticesDataKinds();
  28258. };
  28259. /**
  28260. * Returns a positive integer : the total number of indices in this mesh geometry.
  28261. * Returns zero if the mesh has no geometry.
  28262. */
  28263. Mesh.prototype.getTotalIndices = function () {
  28264. if (!this._geometry) {
  28265. return 0;
  28266. }
  28267. return this._geometry.getTotalIndices();
  28268. };
  28269. /**
  28270. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28271. * 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.
  28272. * Returns an empty array if the mesh has no geometry.
  28273. */
  28274. Mesh.prototype.getIndices = function (copyWhenShared) {
  28275. if (!this._geometry) {
  28276. return [];
  28277. }
  28278. return this._geometry.getIndices(copyWhenShared);
  28279. };
  28280. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28281. get: function () {
  28282. return this._masterMesh !== null && this._masterMesh !== undefined;
  28283. },
  28284. enumerable: true,
  28285. configurable: true
  28286. });
  28287. /**
  28288. * Determine if the current mesh is ready to be rendered
  28289. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28290. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28291. * @returns true if all associated assets are ready (material, textures, shaders)
  28292. */
  28293. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28294. if (completeCheck === void 0) { completeCheck = false; }
  28295. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28296. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28297. return false;
  28298. }
  28299. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28300. return false;
  28301. }
  28302. if (!this.subMeshes || this.subMeshes.length === 0) {
  28303. return true;
  28304. }
  28305. if (!completeCheck) {
  28306. return true;
  28307. }
  28308. var engine = this.getEngine();
  28309. var scene = this.getScene();
  28310. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28311. this.computeWorldMatrix();
  28312. var mat = this.material || scene.defaultMaterial;
  28313. if (mat) {
  28314. if (mat.storeEffectOnSubMeshes) {
  28315. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28316. var subMesh = _a[_i];
  28317. var effectiveMaterial = subMesh.getMaterial();
  28318. if (effectiveMaterial) {
  28319. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28320. return false;
  28321. }
  28322. }
  28323. }
  28324. }
  28325. else {
  28326. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28327. return false;
  28328. }
  28329. }
  28330. }
  28331. // Shadows
  28332. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28333. var light = _c[_b];
  28334. var generator = light.getShadowGenerator();
  28335. if (generator) {
  28336. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28337. var subMesh = _e[_d];
  28338. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28339. return false;
  28340. }
  28341. }
  28342. }
  28343. }
  28344. // LOD
  28345. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28346. var lod = _g[_f];
  28347. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28348. return false;
  28349. }
  28350. }
  28351. return true;
  28352. };
  28353. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28354. /**
  28355. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28356. * This property is pertinent only for updatable parametric shapes.
  28357. */
  28358. get: function () {
  28359. return this._areNormalsFrozen;
  28360. },
  28361. enumerable: true,
  28362. configurable: true
  28363. });
  28364. /**
  28365. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28366. * It has no effect at all on other shapes.
  28367. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28368. * Returns the Mesh.
  28369. */
  28370. Mesh.prototype.freezeNormals = function () {
  28371. this._areNormalsFrozen = true;
  28372. return this;
  28373. };
  28374. /**
  28375. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28376. * It has no effect at all on other shapes.
  28377. * It reactivates the mesh normals computation if it was previously frozen.
  28378. * Returns the Mesh.
  28379. */
  28380. Mesh.prototype.unfreezeNormals = function () {
  28381. this._areNormalsFrozen = false;
  28382. return this;
  28383. };
  28384. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28385. /**
  28386. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28387. */
  28388. set: function (count) {
  28389. this._overridenInstanceCount = count;
  28390. },
  28391. enumerable: true,
  28392. configurable: true
  28393. });
  28394. // Methods
  28395. Mesh.prototype._preActivate = function () {
  28396. var sceneRenderId = this.getScene().getRenderId();
  28397. if (this._preActivateId === sceneRenderId) {
  28398. return this;
  28399. }
  28400. this._preActivateId = sceneRenderId;
  28401. this._visibleInstances = null;
  28402. return this;
  28403. };
  28404. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28405. if (this._visibleInstances) {
  28406. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28407. }
  28408. return this;
  28409. };
  28410. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28411. if (!this._visibleInstances) {
  28412. this._visibleInstances = {};
  28413. this._visibleInstances.defaultRenderId = renderId;
  28414. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28415. }
  28416. if (!this._visibleInstances[renderId]) {
  28417. this._visibleInstances[renderId] = new Array();
  28418. }
  28419. this._visibleInstances[renderId].push(instance);
  28420. return this;
  28421. };
  28422. /**
  28423. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28424. * This means the mesh underlying bounding box and sphere are recomputed.
  28425. * Returns the Mesh.
  28426. */
  28427. Mesh.prototype.refreshBoundingInfo = function () {
  28428. return this._refreshBoundingInfo(false);
  28429. };
  28430. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28431. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28432. return this;
  28433. }
  28434. var data = this._getPositionData(applySkeleton);
  28435. if (data) {
  28436. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28437. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28438. }
  28439. if (this.subMeshes) {
  28440. for (var index = 0; index < this.subMeshes.length; index++) {
  28441. this.subMeshes[index].refreshBoundingInfo();
  28442. }
  28443. }
  28444. this._updateBoundingInfo();
  28445. return this;
  28446. };
  28447. Mesh.prototype._getPositionData = function (applySkeleton) {
  28448. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28449. if (data && applySkeleton && this.skeleton) {
  28450. data = BABYLON.Tools.Slice(data);
  28451. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28452. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28453. if (matricesWeightsData && matricesIndicesData) {
  28454. var needExtras = this.numBoneInfluencers > 4;
  28455. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28456. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28457. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28458. var tempVector = BABYLON.Tmp.Vector3[0];
  28459. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28460. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28461. var matWeightIdx = 0;
  28462. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28463. finalMatrix.reset();
  28464. var inf;
  28465. var weight;
  28466. for (inf = 0; inf < 4; inf++) {
  28467. weight = matricesWeightsData[matWeightIdx + inf];
  28468. if (weight <= 0)
  28469. break;
  28470. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28471. finalMatrix.addToSelf(tempMatrix);
  28472. }
  28473. if (needExtras) {
  28474. for (inf = 0; inf < 4; inf++) {
  28475. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28476. if (weight <= 0)
  28477. break;
  28478. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28479. finalMatrix.addToSelf(tempMatrix);
  28480. }
  28481. }
  28482. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28483. tempVector.toArray(data, index);
  28484. }
  28485. }
  28486. }
  28487. return data;
  28488. };
  28489. Mesh.prototype._createGlobalSubMesh = function (force) {
  28490. var totalVertices = this.getTotalVertices();
  28491. if (!totalVertices || !this.getIndices()) {
  28492. return null;
  28493. }
  28494. // Check if we need to recreate the submeshes
  28495. if (this.subMeshes && this.subMeshes.length > 0) {
  28496. var ib = this.getIndices();
  28497. if (!ib) {
  28498. return null;
  28499. }
  28500. var totalIndices = ib.length;
  28501. var needToRecreate = false;
  28502. if (force) {
  28503. needToRecreate = true;
  28504. }
  28505. else {
  28506. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28507. var submesh = _a[_i];
  28508. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28509. needToRecreate = true;
  28510. break;
  28511. }
  28512. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28513. needToRecreate = true;
  28514. break;
  28515. }
  28516. }
  28517. }
  28518. if (!needToRecreate) {
  28519. return this.subMeshes[0];
  28520. }
  28521. }
  28522. this.releaseSubMeshes();
  28523. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28524. };
  28525. Mesh.prototype.subdivide = function (count) {
  28526. if (count < 1) {
  28527. return;
  28528. }
  28529. var totalIndices = this.getTotalIndices();
  28530. var subdivisionSize = (totalIndices / count) | 0;
  28531. var offset = 0;
  28532. // Ensure that subdivisionSize is a multiple of 3
  28533. while (subdivisionSize % 3 !== 0) {
  28534. subdivisionSize++;
  28535. }
  28536. this.releaseSubMeshes();
  28537. for (var index = 0; index < count; index++) {
  28538. if (offset >= totalIndices) {
  28539. break;
  28540. }
  28541. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28542. offset += subdivisionSize;
  28543. }
  28544. this.synchronizeInstances();
  28545. };
  28546. /**
  28547. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28548. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28549. * The `data` are either a numeric array either a Float32Array.
  28550. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28551. * 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).
  28552. * Note that a new underlying VertexBuffer object is created each call.
  28553. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28554. *
  28555. * Possible `kind` values :
  28556. * - BABYLON.VertexBuffer.PositionKind
  28557. * - BABYLON.VertexBuffer.UVKind
  28558. * - BABYLON.VertexBuffer.UV2Kind
  28559. * - BABYLON.VertexBuffer.UV3Kind
  28560. * - BABYLON.VertexBuffer.UV4Kind
  28561. * - BABYLON.VertexBuffer.UV5Kind
  28562. * - BABYLON.VertexBuffer.UV6Kind
  28563. * - BABYLON.VertexBuffer.ColorKind
  28564. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28565. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28566. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28567. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28568. *
  28569. * Returns the Mesh.
  28570. */
  28571. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28572. if (updatable === void 0) { updatable = false; }
  28573. if (!this._geometry) {
  28574. var vertexData = new BABYLON.VertexData();
  28575. vertexData.set(data, kind);
  28576. var scene = this.getScene();
  28577. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28578. }
  28579. else {
  28580. this._geometry.setVerticesData(kind, data, updatable, stride);
  28581. }
  28582. return this;
  28583. };
  28584. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28585. if (updatable === void 0) { updatable = true; }
  28586. var vb = this.getVertexBuffer(kind);
  28587. if (!vb || vb.isUpdatable() === updatable) {
  28588. return;
  28589. }
  28590. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28591. };
  28592. /**
  28593. * Sets the mesh VertexBuffer.
  28594. * Returns the Mesh.
  28595. */
  28596. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28597. if (!this._geometry) {
  28598. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28599. }
  28600. this._geometry.setVerticesBuffer(buffer);
  28601. return this;
  28602. };
  28603. /**
  28604. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28605. * If the mesh has no geometry, it is simply returned as it is.
  28606. * The `data` are either a numeric array either a Float32Array.
  28607. * No new underlying VertexBuffer object is created.
  28608. * 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.
  28609. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28610. *
  28611. * Possible `kind` values :
  28612. * - BABYLON.VertexBuffer.PositionKind
  28613. * - BABYLON.VertexBuffer.UVKind
  28614. * - BABYLON.VertexBuffer.UV2Kind
  28615. * - BABYLON.VertexBuffer.UV3Kind
  28616. * - BABYLON.VertexBuffer.UV4Kind
  28617. * - BABYLON.VertexBuffer.UV5Kind
  28618. * - BABYLON.VertexBuffer.UV6Kind
  28619. * - BABYLON.VertexBuffer.ColorKind
  28620. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28621. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28622. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28623. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28624. *
  28625. * Returns the Mesh.
  28626. */
  28627. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28628. if (!this._geometry) {
  28629. return this;
  28630. }
  28631. if (!makeItUnique) {
  28632. this._geometry.updateVerticesData(kind, data, updateExtends);
  28633. }
  28634. else {
  28635. this.makeGeometryUnique();
  28636. this.updateVerticesData(kind, data, updateExtends, false);
  28637. }
  28638. return this;
  28639. };
  28640. /**
  28641. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28642. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28643. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28644. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28645. * Returns the Mesh.
  28646. */
  28647. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28648. if (computeNormals === void 0) { computeNormals = true; }
  28649. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28650. if (!positions) {
  28651. return this;
  28652. }
  28653. positionFunction(positions);
  28654. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28655. if (computeNormals) {
  28656. var indices = this.getIndices();
  28657. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28658. if (!normals) {
  28659. return this;
  28660. }
  28661. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28662. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28663. }
  28664. return this;
  28665. };
  28666. /**
  28667. * Creates a un-shared specific occurence of the geometry for the mesh.
  28668. * Returns the Mesh.
  28669. */
  28670. Mesh.prototype.makeGeometryUnique = function () {
  28671. if (!this._geometry) {
  28672. return this;
  28673. }
  28674. var oldGeometry = this._geometry;
  28675. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28676. oldGeometry.releaseForMesh(this, true);
  28677. geometry.applyToMesh(this);
  28678. return this;
  28679. };
  28680. /**
  28681. * Sets the mesh indices.
  28682. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28683. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28684. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28685. * This method creates a new index buffer each call.
  28686. * Returns the Mesh.
  28687. */
  28688. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28689. if (totalVertices === void 0) { totalVertices = null; }
  28690. if (updatable === void 0) { updatable = false; }
  28691. if (!this._geometry) {
  28692. var vertexData = new BABYLON.VertexData();
  28693. vertexData.indices = indices;
  28694. var scene = this.getScene();
  28695. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28696. }
  28697. else {
  28698. this._geometry.setIndices(indices, totalVertices, updatable);
  28699. }
  28700. return this;
  28701. };
  28702. /**
  28703. * Update the current index buffer
  28704. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28705. * Returns the Mesh.
  28706. */
  28707. Mesh.prototype.updateIndices = function (indices, offset) {
  28708. if (!this._geometry) {
  28709. return this;
  28710. }
  28711. this._geometry.updateIndices(indices, offset);
  28712. return this;
  28713. };
  28714. /**
  28715. * Invert the geometry to move from a right handed system to a left handed one.
  28716. * Returns the Mesh.
  28717. */
  28718. Mesh.prototype.toLeftHanded = function () {
  28719. if (!this._geometry) {
  28720. return this;
  28721. }
  28722. this._geometry.toLeftHanded();
  28723. return this;
  28724. };
  28725. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28726. if (!this._geometry) {
  28727. return this;
  28728. }
  28729. var engine = this.getScene().getEngine();
  28730. // Wireframe
  28731. var indexToBind;
  28732. if (this._unIndexed) {
  28733. indexToBind = null;
  28734. }
  28735. else {
  28736. switch (fillMode) {
  28737. case BABYLON.Material.PointFillMode:
  28738. indexToBind = null;
  28739. break;
  28740. case BABYLON.Material.WireFrameFillMode:
  28741. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28742. break;
  28743. default:
  28744. case BABYLON.Material.TriangleFillMode:
  28745. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28746. break;
  28747. }
  28748. }
  28749. // VBOs
  28750. this._geometry._bind(effect, indexToBind);
  28751. return this;
  28752. };
  28753. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28754. if (alternate === void 0) { alternate = false; }
  28755. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28756. return this;
  28757. }
  28758. this.onBeforeDrawObservable.notifyObservers(this);
  28759. var scene = this.getScene();
  28760. var engine = scene.getEngine();
  28761. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28762. // or triangles as points
  28763. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28764. }
  28765. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28766. // Triangles as wireframe
  28767. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28768. }
  28769. else {
  28770. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28771. }
  28772. if (scene._isAlternateRenderingEnabled && !alternate) {
  28773. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28774. if (!effect || !scene.activeCamera) {
  28775. return this;
  28776. }
  28777. scene._switchToAlternateCameraConfiguration(true);
  28778. this._effectiveMaterial.bindView(effect);
  28779. this._effectiveMaterial.bindViewProjection(effect);
  28780. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28781. this._draw(subMesh, fillMode, instancesCount, true);
  28782. engine.setViewport(scene.activeCamera.viewport);
  28783. scene._switchToAlternateCameraConfiguration(false);
  28784. this._effectiveMaterial.bindView(effect);
  28785. this._effectiveMaterial.bindViewProjection(effect);
  28786. }
  28787. return this;
  28788. };
  28789. /**
  28790. * Registers for this mesh a javascript function called just before the rendering process.
  28791. * This function is passed the current mesh.
  28792. * Return the Mesh.
  28793. */
  28794. Mesh.prototype.registerBeforeRender = function (func) {
  28795. this.onBeforeRenderObservable.add(func);
  28796. return this;
  28797. };
  28798. /**
  28799. * Disposes a previously registered javascript function called before the rendering.
  28800. * This function is passed the current mesh.
  28801. * Returns the Mesh.
  28802. */
  28803. Mesh.prototype.unregisterBeforeRender = function (func) {
  28804. this.onBeforeRenderObservable.removeCallback(func);
  28805. return this;
  28806. };
  28807. /**
  28808. * Registers for this mesh a javascript function called just after the rendering is complete.
  28809. * This function is passed the current mesh.
  28810. * Returns the Mesh.
  28811. */
  28812. Mesh.prototype.registerAfterRender = function (func) {
  28813. this.onAfterRenderObservable.add(func);
  28814. return this;
  28815. };
  28816. /**
  28817. * Disposes a previously registered javascript function called after the rendering.
  28818. * This function is passed the current mesh.
  28819. * Return the Mesh.
  28820. */
  28821. Mesh.prototype.unregisterAfterRender = function (func) {
  28822. this.onAfterRenderObservable.removeCallback(func);
  28823. return this;
  28824. };
  28825. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28826. var scene = this.getScene();
  28827. this._batchCache.mustReturn = false;
  28828. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28829. this._batchCache.visibleInstances[subMeshId] = null;
  28830. if (this._visibleInstances) {
  28831. var currentRenderId = scene.getRenderId();
  28832. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28833. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28834. var selfRenderId = this._renderId;
  28835. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28836. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28837. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28838. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28839. }
  28840. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28841. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28842. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28843. this._batchCache.mustReturn = true;
  28844. return this._batchCache;
  28845. }
  28846. if (currentRenderId !== selfRenderId) {
  28847. this._batchCache.renderSelf[subMeshId] = false;
  28848. }
  28849. }
  28850. this._renderIdForInstances[subMeshId] = currentRenderId;
  28851. }
  28852. return this._batchCache;
  28853. };
  28854. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28855. var visibleInstances = batch.visibleInstances[subMesh._id];
  28856. if (!visibleInstances) {
  28857. return this;
  28858. }
  28859. var matricesCount = visibleInstances.length + 1;
  28860. var bufferSize = matricesCount * 16 * 4;
  28861. var currentInstancesBufferSize = this._instancesBufferSize;
  28862. var instancesBuffer = this._instancesBuffer;
  28863. while (this._instancesBufferSize < bufferSize) {
  28864. this._instancesBufferSize *= 2;
  28865. }
  28866. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28867. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28868. }
  28869. var offset = 0;
  28870. var instancesCount = 0;
  28871. var world = this.getWorldMatrix();
  28872. if (batch.renderSelf[subMesh._id]) {
  28873. world.copyToArray(this._instancesData, offset);
  28874. offset += 16;
  28875. instancesCount++;
  28876. }
  28877. if (visibleInstances) {
  28878. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28879. var instance = visibleInstances[instanceIndex];
  28880. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28881. offset += 16;
  28882. instancesCount++;
  28883. }
  28884. }
  28885. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28886. if (instancesBuffer) {
  28887. instancesBuffer.dispose();
  28888. }
  28889. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28890. this._instancesBuffer = instancesBuffer;
  28891. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28892. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28893. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28894. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28895. }
  28896. else {
  28897. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28898. }
  28899. this._bind(subMesh, effect, fillMode);
  28900. this._draw(subMesh, fillMode, instancesCount);
  28901. engine.unbindInstanceAttributes();
  28902. return this;
  28903. };
  28904. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28905. var scene = this.getScene();
  28906. var engine = scene.getEngine();
  28907. if (hardwareInstancedRendering) {
  28908. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28909. }
  28910. else {
  28911. if (batch.renderSelf[subMesh._id]) {
  28912. // Draw
  28913. if (onBeforeDraw) {
  28914. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28915. }
  28916. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28917. }
  28918. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28919. if (visibleInstancesForSubMesh) {
  28920. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28921. var instance = visibleInstancesForSubMesh[instanceIndex];
  28922. // World
  28923. var world = instance.getWorldMatrix();
  28924. if (onBeforeDraw) {
  28925. onBeforeDraw(true, world, effectiveMaterial);
  28926. }
  28927. // Draw
  28928. this._draw(subMesh, fillMode);
  28929. }
  28930. }
  28931. }
  28932. return this;
  28933. };
  28934. /**
  28935. * Triggers the draw call for the mesh.
  28936. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28937. * Returns the Mesh.
  28938. */
  28939. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28940. this.checkOcclusionQuery();
  28941. if (this._isOccluded) {
  28942. return this;
  28943. }
  28944. var scene = this.getScene();
  28945. // Managing instances
  28946. var batch = this._getInstancesRenderList(subMesh._id);
  28947. if (batch.mustReturn) {
  28948. return this;
  28949. }
  28950. // Checking geometry state
  28951. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28952. return this;
  28953. }
  28954. this.onBeforeRenderObservable.notifyObservers(this);
  28955. var engine = scene.getEngine();
  28956. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28957. // Material
  28958. var material = subMesh.getMaterial();
  28959. if (!material) {
  28960. return this;
  28961. }
  28962. this._effectiveMaterial = material;
  28963. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28964. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28965. return this;
  28966. }
  28967. }
  28968. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28969. return this;
  28970. }
  28971. // Alpha mode
  28972. if (enableAlphaMode) {
  28973. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28974. }
  28975. // Outline - step 1
  28976. var savedDepthWrite = engine.getDepthWrite();
  28977. if (this.renderOutline) {
  28978. engine.setDepthWrite(false);
  28979. scene.getOutlineRenderer().render(subMesh, batch);
  28980. engine.setDepthWrite(savedDepthWrite);
  28981. }
  28982. var effect;
  28983. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28984. effect = subMesh.effect;
  28985. }
  28986. else {
  28987. effect = this._effectiveMaterial.getEffect();
  28988. }
  28989. if (!effect) {
  28990. return this;
  28991. }
  28992. var sideOrientation = this.overrideMaterialSideOrientation;
  28993. if (sideOrientation == null) {
  28994. sideOrientation = this._effectiveMaterial.sideOrientation;
  28995. if (this._getWorldMatrixDeterminant() < 0) {
  28996. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28997. }
  28998. }
  28999. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29000. if (this._effectiveMaterial.forceDepthWrite) {
  29001. engine.setDepthWrite(true);
  29002. }
  29003. // Bind
  29004. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29005. if (!hardwareInstancedRendering) {
  29006. this._bind(subMesh, effect, fillMode);
  29007. }
  29008. var world = this.getWorldMatrix();
  29009. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29010. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29011. }
  29012. else {
  29013. this._effectiveMaterial.bind(world, this);
  29014. }
  29015. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29016. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29017. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29018. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29019. }
  29020. // Draw
  29021. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29022. // Unbind
  29023. this._effectiveMaterial.unbind();
  29024. // Outline - step 2
  29025. if (this.renderOutline && savedDepthWrite) {
  29026. engine.setDepthWrite(true);
  29027. engine.setColorWrite(false);
  29028. scene.getOutlineRenderer().render(subMesh, batch);
  29029. engine.setColorWrite(true);
  29030. }
  29031. // Overlay
  29032. if (this.renderOverlay) {
  29033. var currentMode = engine.getAlphaMode();
  29034. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29035. scene.getOutlineRenderer().render(subMesh, batch, true);
  29036. engine.setAlphaMode(currentMode);
  29037. }
  29038. this.onAfterRenderObservable.notifyObservers(this);
  29039. return this;
  29040. };
  29041. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29042. if (isInstance && effectiveMaterial) {
  29043. effectiveMaterial.bindOnlyWorldMatrix(world);
  29044. }
  29045. };
  29046. /**
  29047. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29048. */
  29049. Mesh.prototype.getEmittedParticleSystems = function () {
  29050. var results = new Array();
  29051. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29052. var particleSystem = this.getScene().particleSystems[index];
  29053. if (particleSystem.emitter === this) {
  29054. results.push(particleSystem);
  29055. }
  29056. }
  29057. return results;
  29058. };
  29059. /**
  29060. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29061. */
  29062. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29063. var results = new Array();
  29064. var descendants = this.getDescendants();
  29065. descendants.push(this);
  29066. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29067. var particleSystem = this.getScene().particleSystems[index];
  29068. var emitter = particleSystem.emitter;
  29069. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29070. results.push(particleSystem);
  29071. }
  29072. }
  29073. return results;
  29074. };
  29075. Mesh.prototype._checkDelayState = function () {
  29076. var scene = this.getScene();
  29077. if (this._geometry) {
  29078. this._geometry.load(scene);
  29079. }
  29080. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29081. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29082. this._queueLoad(scene);
  29083. }
  29084. return this;
  29085. };
  29086. Mesh.prototype._queueLoad = function (scene) {
  29087. var _this = this;
  29088. scene._addPendingData(this);
  29089. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29090. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29091. if (data instanceof ArrayBuffer) {
  29092. _this._delayLoadingFunction(data, _this);
  29093. }
  29094. else {
  29095. _this._delayLoadingFunction(JSON.parse(data), _this);
  29096. }
  29097. _this.instances.forEach(function (instance) {
  29098. instance._syncSubMeshes();
  29099. });
  29100. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29101. scene._removePendingData(_this);
  29102. }, function () { }, scene.database, getBinaryData);
  29103. return this;
  29104. };
  29105. /**
  29106. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29107. */
  29108. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29109. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29110. return false;
  29111. }
  29112. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29113. return false;
  29114. }
  29115. this._checkDelayState();
  29116. return true;
  29117. };
  29118. /**
  29119. * Sets the mesh material by the material or multiMaterial `id` property.
  29120. * The material `id` is a string identifying the material or the multiMaterial.
  29121. * This method returns the Mesh.
  29122. */
  29123. Mesh.prototype.setMaterialByID = function (id) {
  29124. var materials = this.getScene().materials;
  29125. var index;
  29126. for (index = materials.length - 1; index > -1; index--) {
  29127. if (materials[index].id === id) {
  29128. this.material = materials[index];
  29129. return this;
  29130. }
  29131. }
  29132. // Multi
  29133. var multiMaterials = this.getScene().multiMaterials;
  29134. for (index = multiMaterials.length - 1; index > -1; index--) {
  29135. if (multiMaterials[index].id === id) {
  29136. this.material = multiMaterials[index];
  29137. return this;
  29138. }
  29139. }
  29140. return this;
  29141. };
  29142. /**
  29143. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29144. */
  29145. Mesh.prototype.getAnimatables = function () {
  29146. var results = new Array();
  29147. if (this.material) {
  29148. results.push(this.material);
  29149. }
  29150. if (this.skeleton) {
  29151. results.push(this.skeleton);
  29152. }
  29153. return results;
  29154. };
  29155. /**
  29156. * Modifies the mesh geometry according to the passed transformation matrix.
  29157. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29158. * The mesh normals are modified accordingly the same transformation.
  29159. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29160. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29161. * Returns the Mesh.
  29162. */
  29163. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29164. // Position
  29165. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29166. return this;
  29167. }
  29168. var submeshes = this.subMeshes.splice(0);
  29169. this._resetPointsArrayCache();
  29170. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29171. var temp = new Array();
  29172. var index;
  29173. for (index = 0; index < data.length; index += 3) {
  29174. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29175. }
  29176. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29177. // Normals
  29178. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29179. return this;
  29180. }
  29181. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29182. temp = [];
  29183. for (index = 0; index < data.length; index += 3) {
  29184. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29185. }
  29186. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29187. // flip faces?
  29188. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29189. this.flipFaces();
  29190. }
  29191. // Restore submeshes
  29192. this.releaseSubMeshes();
  29193. this.subMeshes = submeshes;
  29194. return this;
  29195. };
  29196. /**
  29197. * Modifies the mesh geometry according to its own current World Matrix.
  29198. * The mesh World Matrix is then reset.
  29199. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29200. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29201. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29202. * Returns the Mesh.
  29203. */
  29204. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29205. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29206. this.scaling.copyFromFloats(1, 1, 1);
  29207. this.position.copyFromFloats(0, 0, 0);
  29208. this.rotation.copyFromFloats(0, 0, 0);
  29209. //only if quaternion is already set
  29210. if (this.rotationQuaternion) {
  29211. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29212. }
  29213. this._worldMatrix = BABYLON.Matrix.Identity();
  29214. return this;
  29215. };
  29216. Object.defineProperty(Mesh.prototype, "_positions", {
  29217. // Cache
  29218. get: function () {
  29219. if (this._geometry) {
  29220. return this._geometry._positions;
  29221. }
  29222. return null;
  29223. },
  29224. enumerable: true,
  29225. configurable: true
  29226. });
  29227. Mesh.prototype._resetPointsArrayCache = function () {
  29228. if (this._geometry) {
  29229. this._geometry._resetPointsArrayCache();
  29230. }
  29231. return this;
  29232. };
  29233. Mesh.prototype._generatePointsArray = function () {
  29234. if (this._geometry) {
  29235. return this._geometry._generatePointsArray();
  29236. }
  29237. return false;
  29238. };
  29239. /**
  29240. * Returns a new Mesh object generated from the current mesh properties.
  29241. * This method must not get confused with createInstance().
  29242. * The parameter `name` is a string, the name given to the new mesh.
  29243. * The optional parameter `newParent` can be any Node object (default `null`).
  29244. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29245. * 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.
  29246. */
  29247. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29248. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29249. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29250. };
  29251. /**
  29252. * Releases resources associated with this mesh.
  29253. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29254. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29255. */
  29256. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29257. var _this = this;
  29258. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29259. this.morphTargetManager = null;
  29260. if (this._geometry) {
  29261. this._geometry.releaseForMesh(this, true);
  29262. }
  29263. // Sources
  29264. var meshes = this.getScene().meshes;
  29265. meshes.forEach(function (abstractMesh) {
  29266. var mesh = abstractMesh;
  29267. if (mesh._source && mesh._source === _this) {
  29268. mesh._source = null;
  29269. }
  29270. });
  29271. this._source = null;
  29272. // Instances
  29273. if (this._instancesBuffer) {
  29274. this._instancesBuffer.dispose();
  29275. this._instancesBuffer = null;
  29276. }
  29277. while (this.instances.length) {
  29278. this.instances[0].dispose();
  29279. }
  29280. // Effect layers.
  29281. var effectLayers = this.getScene().effectLayers;
  29282. for (var i = 0; i < effectLayers.length; i++) {
  29283. var effectLayer = effectLayers[i];
  29284. if (effectLayer) {
  29285. effectLayer._disposeMesh(this);
  29286. }
  29287. }
  29288. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29289. };
  29290. /**
  29291. * Modifies the mesh geometry according to a displacement map.
  29292. * 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.
  29293. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29294. * This method returns nothing.
  29295. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29296. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29297. * 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.
  29298. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29299. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29300. *
  29301. * Returns the Mesh.
  29302. */
  29303. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29304. var _this = this;
  29305. var scene = this.getScene();
  29306. var onload = function (img) {
  29307. // Getting height map data
  29308. var canvas = document.createElement("canvas");
  29309. var context = canvas.getContext("2d");
  29310. var heightMapWidth = img.width;
  29311. var heightMapHeight = img.height;
  29312. canvas.width = heightMapWidth;
  29313. canvas.height = heightMapHeight;
  29314. context.drawImage(img, 0, 0);
  29315. // Create VertexData from map data
  29316. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29317. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29318. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29319. //execute success callback, if set
  29320. if (onSuccess) {
  29321. onSuccess(_this);
  29322. }
  29323. };
  29324. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29325. return this;
  29326. };
  29327. /**
  29328. * Modifies the mesh geometry according to a displacementMap buffer.
  29329. * 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.
  29330. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29331. * This method returns nothing.
  29332. * 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.
  29333. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29334. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29335. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29336. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29337. *
  29338. * Returns the Mesh.
  29339. */
  29340. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29341. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29342. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29343. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29344. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29345. return this;
  29346. }
  29347. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29348. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29349. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29350. var position = BABYLON.Vector3.Zero();
  29351. var normal = BABYLON.Vector3.Zero();
  29352. var uv = BABYLON.Vector2.Zero();
  29353. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29354. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29355. for (var index = 0; index < positions.length; index += 3) {
  29356. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29357. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29358. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29359. // Compute height
  29360. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29361. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29362. var pos = (u + v * heightMapWidth) * 4;
  29363. var r = buffer[pos] / 255.0;
  29364. var g = buffer[pos + 1] / 255.0;
  29365. var b = buffer[pos + 2] / 255.0;
  29366. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29367. normal.normalize();
  29368. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29369. position = position.add(normal);
  29370. position.toArray(positions, index);
  29371. }
  29372. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29373. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29374. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29375. return this;
  29376. };
  29377. /**
  29378. * Modify the mesh to get a flat shading rendering.
  29379. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29380. * This method returns the Mesh.
  29381. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29382. */
  29383. Mesh.prototype.convertToFlatShadedMesh = function () {
  29384. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29385. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29386. var kinds = this.getVerticesDataKinds();
  29387. var vbs = {};
  29388. var data = {};
  29389. var newdata = {};
  29390. var updatableNormals = false;
  29391. var kindIndex;
  29392. var kind;
  29393. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29394. kind = kinds[kindIndex];
  29395. var vertexBuffer = this.getVertexBuffer(kind);
  29396. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29397. updatableNormals = vertexBuffer.isUpdatable();
  29398. kinds.splice(kindIndex, 1);
  29399. kindIndex--;
  29400. continue;
  29401. }
  29402. vbs[kind] = vertexBuffer;
  29403. data[kind] = vbs[kind].getData();
  29404. newdata[kind] = [];
  29405. }
  29406. // Save previous submeshes
  29407. var previousSubmeshes = this.subMeshes.slice(0);
  29408. var indices = this.getIndices();
  29409. var totalIndices = this.getTotalIndices();
  29410. // Generating unique vertices per face
  29411. var index;
  29412. for (index = 0; index < totalIndices; index++) {
  29413. var vertexIndex = indices[index];
  29414. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29415. kind = kinds[kindIndex];
  29416. var stride = vbs[kind].getStrideSize();
  29417. for (var offset = 0; offset < stride; offset++) {
  29418. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29419. }
  29420. }
  29421. }
  29422. // Updating faces & normal
  29423. var normals = [];
  29424. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29425. for (index = 0; index < totalIndices; index += 3) {
  29426. indices[index] = index;
  29427. indices[index + 1] = index + 1;
  29428. indices[index + 2] = index + 2;
  29429. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29430. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29431. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29432. var p1p2 = p1.subtract(p2);
  29433. var p3p2 = p3.subtract(p2);
  29434. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29435. // Store same normals for every vertex
  29436. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29437. normals.push(normal.x);
  29438. normals.push(normal.y);
  29439. normals.push(normal.z);
  29440. }
  29441. }
  29442. this.setIndices(indices);
  29443. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29444. // Updating vertex buffers
  29445. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29446. kind = kinds[kindIndex];
  29447. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29448. }
  29449. // Updating submeshes
  29450. this.releaseSubMeshes();
  29451. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29452. var previousOne = previousSubmeshes[submeshIndex];
  29453. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29454. }
  29455. this.synchronizeInstances();
  29456. return this;
  29457. };
  29458. /**
  29459. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29460. * In other words, more vertices, no more indices and a single bigger VBO.
  29461. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29462. * Returns the Mesh.
  29463. */
  29464. Mesh.prototype.convertToUnIndexedMesh = function () {
  29465. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29466. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29467. var kinds = this.getVerticesDataKinds();
  29468. var vbs = {};
  29469. var data = {};
  29470. var newdata = {};
  29471. var kindIndex;
  29472. var kind;
  29473. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29474. kind = kinds[kindIndex];
  29475. var vertexBuffer = this.getVertexBuffer(kind);
  29476. vbs[kind] = vertexBuffer;
  29477. data[kind] = vbs[kind].getData();
  29478. newdata[kind] = [];
  29479. }
  29480. // Save previous submeshes
  29481. var previousSubmeshes = this.subMeshes.slice(0);
  29482. var indices = this.getIndices();
  29483. var totalIndices = this.getTotalIndices();
  29484. // Generating unique vertices per face
  29485. var index;
  29486. for (index = 0; index < totalIndices; index++) {
  29487. var vertexIndex = indices[index];
  29488. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29489. kind = kinds[kindIndex];
  29490. var stride = vbs[kind].getStrideSize();
  29491. for (var offset = 0; offset < stride; offset++) {
  29492. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29493. }
  29494. }
  29495. }
  29496. // Updating indices
  29497. for (index = 0; index < totalIndices; index += 3) {
  29498. indices[index] = index;
  29499. indices[index + 1] = index + 1;
  29500. indices[index + 2] = index + 2;
  29501. }
  29502. this.setIndices(indices);
  29503. // Updating vertex buffers
  29504. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29505. kind = kinds[kindIndex];
  29506. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29507. }
  29508. // Updating submeshes
  29509. this.releaseSubMeshes();
  29510. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29511. var previousOne = previousSubmeshes[submeshIndex];
  29512. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29513. }
  29514. this._unIndexed = true;
  29515. this.synchronizeInstances();
  29516. return this;
  29517. };
  29518. /**
  29519. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29520. * This method returns the Mesh.
  29521. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29522. */
  29523. Mesh.prototype.flipFaces = function (flipNormals) {
  29524. if (flipNormals === void 0) { flipNormals = false; }
  29525. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29526. var i;
  29527. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29528. for (i = 0; i < vertex_data.normals.length; i++) {
  29529. vertex_data.normals[i] *= -1;
  29530. }
  29531. }
  29532. if (vertex_data.indices) {
  29533. var temp;
  29534. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29535. // reassign indices
  29536. temp = vertex_data.indices[i + 1];
  29537. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29538. vertex_data.indices[i + 2] = temp;
  29539. }
  29540. }
  29541. vertex_data.applyToMesh(this);
  29542. return this;
  29543. };
  29544. // Instances
  29545. /**
  29546. * Creates a new InstancedMesh object from the mesh model.
  29547. * An instance shares the same properties and the same material than its model.
  29548. * Only these properties of each instance can then be set individually :
  29549. * - position
  29550. * - rotation
  29551. * - rotationQuaternion
  29552. * - setPivotMatrix
  29553. * - scaling
  29554. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29555. * Warning : this method is not supported for Line mesh and LineSystem
  29556. */
  29557. Mesh.prototype.createInstance = function (name) {
  29558. return new BABYLON.InstancedMesh(name, this);
  29559. };
  29560. /**
  29561. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29562. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29563. * This method returns the Mesh.
  29564. */
  29565. Mesh.prototype.synchronizeInstances = function () {
  29566. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29567. var instance = this.instances[instanceIndex];
  29568. instance._syncSubMeshes();
  29569. }
  29570. return this;
  29571. };
  29572. /**
  29573. * Simplify the mesh according to the given array of settings.
  29574. * Function will return immediately and will simplify async. It returns the Mesh.
  29575. * @param settings a collection of simplification settings.
  29576. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29577. * @param type the type of simplification to run.
  29578. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29579. */
  29580. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29581. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29582. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29583. this.getScene().simplificationQueue.addTask({
  29584. settings: settings,
  29585. parallelProcessing: parallelProcessing,
  29586. mesh: this,
  29587. simplificationType: simplificationType,
  29588. successCallback: successCallback
  29589. });
  29590. return this;
  29591. };
  29592. /**
  29593. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29594. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29595. * This should be used together with the simplification to avoid disappearing triangles.
  29596. * Returns the Mesh.
  29597. * @param successCallback an optional success callback to be called after the optimization finished.
  29598. */
  29599. Mesh.prototype.optimizeIndices = function (successCallback) {
  29600. var _this = this;
  29601. var indices = this.getIndices();
  29602. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29603. if (!positions || !indices) {
  29604. return this;
  29605. }
  29606. var vectorPositions = new Array();
  29607. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29608. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29609. }
  29610. var dupes = new Array();
  29611. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29612. var realPos = vectorPositions.length - 1 - iteration;
  29613. var testedPosition = vectorPositions[realPos];
  29614. for (var j = 0; j < realPos; ++j) {
  29615. var againstPosition = vectorPositions[j];
  29616. if (testedPosition.equals(againstPosition)) {
  29617. dupes[realPos] = j;
  29618. break;
  29619. }
  29620. }
  29621. }, function () {
  29622. for (var i = 0; i < indices.length; ++i) {
  29623. indices[i] = dupes[indices[i]] || indices[i];
  29624. }
  29625. //indices are now reordered
  29626. var originalSubMeshes = _this.subMeshes.slice(0);
  29627. _this.setIndices(indices);
  29628. _this.subMeshes = originalSubMeshes;
  29629. if (successCallback) {
  29630. successCallback(_this);
  29631. }
  29632. });
  29633. return this;
  29634. };
  29635. Mesh.prototype.serialize = function (serializationObject) {
  29636. serializationObject.name = this.name;
  29637. serializationObject.id = this.id;
  29638. serializationObject.type = this.getClassName();
  29639. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29640. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29641. }
  29642. serializationObject.position = this.position.asArray();
  29643. if (this.rotationQuaternion) {
  29644. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29645. }
  29646. else if (this.rotation) {
  29647. serializationObject.rotation = this.rotation.asArray();
  29648. }
  29649. serializationObject.scaling = this.scaling.asArray();
  29650. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29651. serializationObject.isEnabled = this.isEnabled(false);
  29652. serializationObject.isVisible = this.isVisible;
  29653. serializationObject.infiniteDistance = this.infiniteDistance;
  29654. serializationObject.pickable = this.isPickable;
  29655. serializationObject.receiveShadows = this.receiveShadows;
  29656. serializationObject.billboardMode = this.billboardMode;
  29657. serializationObject.visibility = this.visibility;
  29658. serializationObject.checkCollisions = this.checkCollisions;
  29659. serializationObject.isBlocker = this.isBlocker;
  29660. // Parent
  29661. if (this.parent) {
  29662. serializationObject.parentId = this.parent.id;
  29663. }
  29664. // Geometry
  29665. serializationObject.isUnIndexed = this.isUnIndexed;
  29666. var geometry = this._geometry;
  29667. if (geometry) {
  29668. var geometryId = geometry.id;
  29669. serializationObject.geometryId = geometryId;
  29670. // SubMeshes
  29671. serializationObject.subMeshes = [];
  29672. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29673. var subMesh = this.subMeshes[subIndex];
  29674. serializationObject.subMeshes.push({
  29675. materialIndex: subMesh.materialIndex,
  29676. verticesStart: subMesh.verticesStart,
  29677. verticesCount: subMesh.verticesCount,
  29678. indexStart: subMesh.indexStart,
  29679. indexCount: subMesh.indexCount
  29680. });
  29681. }
  29682. }
  29683. // Material
  29684. if (this.material) {
  29685. serializationObject.materialId = this.material.id;
  29686. }
  29687. else {
  29688. this.material = null;
  29689. }
  29690. // Morph targets
  29691. if (this.morphTargetManager) {
  29692. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29693. }
  29694. // Skeleton
  29695. if (this.skeleton) {
  29696. serializationObject.skeletonId = this.skeleton.id;
  29697. }
  29698. // Physics
  29699. //TODO implement correct serialization for physics impostors.
  29700. var impostor = this.getPhysicsImpostor();
  29701. if (impostor) {
  29702. serializationObject.physicsMass = impostor.getParam("mass");
  29703. serializationObject.physicsFriction = impostor.getParam("friction");
  29704. serializationObject.physicsRestitution = impostor.getParam("mass");
  29705. serializationObject.physicsImpostor = impostor.type;
  29706. }
  29707. // Metadata
  29708. if (this.metadata) {
  29709. serializationObject.metadata = this.metadata;
  29710. }
  29711. // Instances
  29712. serializationObject.instances = [];
  29713. for (var index = 0; index < this.instances.length; index++) {
  29714. var instance = this.instances[index];
  29715. var serializationInstance = {
  29716. name: instance.name,
  29717. id: instance.id,
  29718. position: instance.position.asArray(),
  29719. scaling: instance.scaling.asArray()
  29720. };
  29721. if (instance.rotationQuaternion) {
  29722. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29723. }
  29724. else if (instance.rotation) {
  29725. serializationInstance.rotation = instance.rotation.asArray();
  29726. }
  29727. serializationObject.instances.push(serializationInstance);
  29728. // Animations
  29729. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29730. serializationInstance.ranges = instance.serializeAnimationRanges();
  29731. }
  29732. //
  29733. // Animations
  29734. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29735. serializationObject.ranges = this.serializeAnimationRanges();
  29736. // Layer mask
  29737. serializationObject.layerMask = this.layerMask;
  29738. // Alpha
  29739. serializationObject.alphaIndex = this.alphaIndex;
  29740. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29741. // Overlay
  29742. serializationObject.overlayAlpha = this.overlayAlpha;
  29743. serializationObject.overlayColor = this.overlayColor.asArray();
  29744. serializationObject.renderOverlay = this.renderOverlay;
  29745. // Fog
  29746. serializationObject.applyFog = this.applyFog;
  29747. // Action Manager
  29748. if (this.actionManager) {
  29749. serializationObject.actions = this.actionManager.serialize(this.name);
  29750. }
  29751. };
  29752. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29753. if (!this.geometry) {
  29754. return;
  29755. }
  29756. this._markSubMeshesAsAttributesDirty();
  29757. var morphTargetManager = this._morphTargetManager;
  29758. if (morphTargetManager && morphTargetManager.vertexCount) {
  29759. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29760. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29761. this.morphTargetManager = null;
  29762. return;
  29763. }
  29764. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29765. var morphTarget = morphTargetManager.getActiveTarget(index);
  29766. var positions = morphTarget.getPositions();
  29767. if (!positions) {
  29768. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29769. return;
  29770. }
  29771. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29772. var normals = morphTarget.getNormals();
  29773. if (normals) {
  29774. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29775. }
  29776. var tangents = morphTarget.getTangents();
  29777. if (tangents) {
  29778. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29779. }
  29780. }
  29781. }
  29782. else {
  29783. var index = 0;
  29784. // Positions
  29785. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29786. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29787. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29788. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29789. }
  29790. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29791. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29792. }
  29793. index++;
  29794. }
  29795. }
  29796. };
  29797. // Statics
  29798. /**
  29799. * Returns a new Mesh object parsed from the source provided.
  29800. * The parameter `parsedMesh` is the source.
  29801. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29802. */
  29803. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29804. var mesh;
  29805. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29806. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29807. }
  29808. else {
  29809. mesh = new Mesh(parsedMesh.name, scene);
  29810. }
  29811. mesh.id = parsedMesh.id;
  29812. if (BABYLON.Tags) {
  29813. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29814. }
  29815. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29816. if (parsedMesh.metadata !== undefined) {
  29817. mesh.metadata = parsedMesh.metadata;
  29818. }
  29819. if (parsedMesh.rotationQuaternion) {
  29820. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29821. }
  29822. else if (parsedMesh.rotation) {
  29823. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29824. }
  29825. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29826. if (parsedMesh.localMatrix) {
  29827. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29828. }
  29829. else if (parsedMesh.pivotMatrix) {
  29830. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29831. }
  29832. mesh.setEnabled(parsedMesh.isEnabled);
  29833. mesh.isVisible = parsedMesh.isVisible;
  29834. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29835. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29836. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29837. if (parsedMesh.applyFog !== undefined) {
  29838. mesh.applyFog = parsedMesh.applyFog;
  29839. }
  29840. if (parsedMesh.pickable !== undefined) {
  29841. mesh.isPickable = parsedMesh.pickable;
  29842. }
  29843. if (parsedMesh.alphaIndex !== undefined) {
  29844. mesh.alphaIndex = parsedMesh.alphaIndex;
  29845. }
  29846. mesh.receiveShadows = parsedMesh.receiveShadows;
  29847. mesh.billboardMode = parsedMesh.billboardMode;
  29848. if (parsedMesh.visibility !== undefined) {
  29849. mesh.visibility = parsedMesh.visibility;
  29850. }
  29851. mesh.checkCollisions = parsedMesh.checkCollisions;
  29852. if (parsedMesh.isBlocker !== undefined) {
  29853. mesh.isBlocker = parsedMesh.isBlocker;
  29854. }
  29855. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29856. // freezeWorldMatrix
  29857. if (parsedMesh.freezeWorldMatrix) {
  29858. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29859. }
  29860. // Parent
  29861. if (parsedMesh.parentId) {
  29862. mesh._waitingParentId = parsedMesh.parentId;
  29863. }
  29864. // Actions
  29865. if (parsedMesh.actions !== undefined) {
  29866. mesh._waitingActions = parsedMesh.actions;
  29867. }
  29868. // Overlay
  29869. if (parsedMesh.overlayAlpha !== undefined) {
  29870. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29871. }
  29872. if (parsedMesh.overlayColor !== undefined) {
  29873. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29874. }
  29875. if (parsedMesh.renderOverlay !== undefined) {
  29876. mesh.renderOverlay = parsedMesh.renderOverlay;
  29877. }
  29878. // Geometry
  29879. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29880. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29881. if (parsedMesh.delayLoadingFile) {
  29882. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29883. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29884. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29885. if (parsedMesh._binaryInfo) {
  29886. mesh._binaryInfo = parsedMesh._binaryInfo;
  29887. }
  29888. mesh._delayInfo = [];
  29889. if (parsedMesh.hasUVs) {
  29890. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29891. }
  29892. if (parsedMesh.hasUVs2) {
  29893. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29894. }
  29895. if (parsedMesh.hasUVs3) {
  29896. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29897. }
  29898. if (parsedMesh.hasUVs4) {
  29899. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29900. }
  29901. if (parsedMesh.hasUVs5) {
  29902. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29903. }
  29904. if (parsedMesh.hasUVs6) {
  29905. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29906. }
  29907. if (parsedMesh.hasColors) {
  29908. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29909. }
  29910. if (parsedMesh.hasMatricesIndices) {
  29911. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29912. }
  29913. if (parsedMesh.hasMatricesWeights) {
  29914. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29915. }
  29916. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29917. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29918. mesh._checkDelayState();
  29919. }
  29920. }
  29921. else {
  29922. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29923. }
  29924. // Material
  29925. if (parsedMesh.materialId) {
  29926. mesh.setMaterialByID(parsedMesh.materialId);
  29927. }
  29928. else {
  29929. mesh.material = null;
  29930. }
  29931. // Morph targets
  29932. if (parsedMesh.morphTargetManagerId > -1) {
  29933. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29934. }
  29935. // Skeleton
  29936. if (parsedMesh.skeletonId > -1) {
  29937. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29938. if (parsedMesh.numBoneInfluencers) {
  29939. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29940. }
  29941. }
  29942. // Animations
  29943. if (parsedMesh.animations) {
  29944. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29945. var parsedAnimation = parsedMesh.animations[animationIndex];
  29946. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29947. }
  29948. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29949. }
  29950. if (parsedMesh.autoAnimate) {
  29951. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29952. }
  29953. // Layer Mask
  29954. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29955. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29956. }
  29957. else {
  29958. mesh.layerMask = 0x0FFFFFFF;
  29959. }
  29960. // Physics
  29961. if (parsedMesh.physicsImpostor) {
  29962. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29963. mass: parsedMesh.physicsMass,
  29964. friction: parsedMesh.physicsFriction,
  29965. restitution: parsedMesh.physicsRestitution
  29966. }, scene);
  29967. }
  29968. // Instances
  29969. if (parsedMesh.instances) {
  29970. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29971. var parsedInstance = parsedMesh.instances[index];
  29972. var instance = mesh.createInstance(parsedInstance.name);
  29973. if (parsedInstance.id) {
  29974. instance.id = parsedInstance.id;
  29975. }
  29976. if (BABYLON.Tags) {
  29977. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29978. }
  29979. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29980. if (parsedInstance.parentId) {
  29981. instance._waitingParentId = parsedInstance.parentId;
  29982. }
  29983. if (parsedInstance.rotationQuaternion) {
  29984. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29985. }
  29986. else if (parsedInstance.rotation) {
  29987. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29988. }
  29989. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29990. instance.checkCollisions = mesh.checkCollisions;
  29991. if (parsedMesh.animations) {
  29992. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29993. parsedAnimation = parsedMesh.animations[animationIndex];
  29994. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29995. }
  29996. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29997. }
  29998. }
  29999. }
  30000. return mesh;
  30001. };
  30002. /**
  30003. * Creates a ribbon mesh.
  30004. * Please consider using the same method from the MeshBuilder class instead.
  30005. * 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.
  30006. *
  30007. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30008. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30009. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30010. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30011. * 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.
  30012. * 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.
  30013. * 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
  30014. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30015. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30016. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30017. */
  30018. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30019. if (closeArray === void 0) { closeArray = false; }
  30020. if (updatable === void 0) { updatable = false; }
  30021. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30022. pathArray: pathArray,
  30023. closeArray: closeArray,
  30024. closePath: closePath,
  30025. offset: offset,
  30026. updatable: updatable,
  30027. sideOrientation: sideOrientation,
  30028. instance: instance
  30029. }, scene);
  30030. };
  30031. /**
  30032. * Creates a plane polygonal mesh. By default, this is a disc.
  30033. * Please consider using the same method from the MeshBuilder class instead.
  30034. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30035. * 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.
  30036. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30037. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30038. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30039. */
  30040. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30041. if (scene === void 0) { scene = null; }
  30042. var options = {
  30043. radius: radius,
  30044. tessellation: tessellation,
  30045. sideOrientation: sideOrientation,
  30046. updatable: updatable
  30047. };
  30048. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30049. };
  30050. /**
  30051. * Creates a box mesh.
  30052. * Please consider using the same method from the MeshBuilder class instead.
  30053. * The parameter `size` sets the size (float) of each box side (default 1).
  30054. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30055. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30056. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30057. */
  30058. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30059. if (scene === void 0) { scene = null; }
  30060. var options = {
  30061. size: size,
  30062. sideOrientation: sideOrientation,
  30063. updatable: updatable
  30064. };
  30065. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30066. };
  30067. /**
  30068. * Creates a sphere mesh.
  30069. * Please consider using the same method from the MeshBuilder class instead.
  30070. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30071. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30072. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30073. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30074. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30075. */
  30076. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30077. var options = {
  30078. segments: segments,
  30079. diameterX: diameter,
  30080. diameterY: diameter,
  30081. diameterZ: diameter,
  30082. sideOrientation: sideOrientation,
  30083. updatable: updatable
  30084. };
  30085. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30086. };
  30087. /**
  30088. * Creates a cylinder or a cone mesh.
  30089. * Please consider using the same method from the MeshBuilder class instead.
  30090. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30091. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30092. * 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.
  30093. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30094. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30095. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30096. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30097. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30098. */
  30099. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30100. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30101. if (scene !== undefined) {
  30102. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30103. updatable = scene;
  30104. }
  30105. scene = subdivisions;
  30106. subdivisions = 1;
  30107. }
  30108. var options = {
  30109. height: height,
  30110. diameterTop: diameterTop,
  30111. diameterBottom: diameterBottom,
  30112. tessellation: tessellation,
  30113. subdivisions: subdivisions,
  30114. sideOrientation: sideOrientation,
  30115. updatable: updatable
  30116. };
  30117. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30118. };
  30119. // Torus (Code from SharpDX.org)
  30120. /**
  30121. * Creates a torus mesh.
  30122. * Please consider using the same method from the MeshBuilder class instead.
  30123. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30124. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30125. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30126. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30127. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30129. */
  30130. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30131. var options = {
  30132. diameter: diameter,
  30133. thickness: thickness,
  30134. tessellation: tessellation,
  30135. sideOrientation: sideOrientation,
  30136. updatable: updatable
  30137. };
  30138. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30139. };
  30140. /**
  30141. * Creates a torus knot mesh.
  30142. * Please consider using the same method from the MeshBuilder class instead.
  30143. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30144. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30145. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30146. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30147. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30148. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30149. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30150. */
  30151. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30152. var options = {
  30153. radius: radius,
  30154. tube: tube,
  30155. radialSegments: radialSegments,
  30156. tubularSegments: tubularSegments,
  30157. p: p,
  30158. q: q,
  30159. sideOrientation: sideOrientation,
  30160. updatable: updatable
  30161. };
  30162. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30163. };
  30164. /**
  30165. * Creates a line mesh.
  30166. * Please consider using the same method from the MeshBuilder class instead.
  30167. * 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.
  30168. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30169. * The parameter `points` is an array successive Vector3.
  30170. * 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
  30171. * When updating an instance, remember that only point positions can change, not the number of points.
  30172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30173. */
  30174. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30175. if (scene === void 0) { scene = null; }
  30176. if (updatable === void 0) { updatable = false; }
  30177. if (instance === void 0) { instance = null; }
  30178. var options = {
  30179. points: points,
  30180. updatable: updatable,
  30181. instance: instance
  30182. };
  30183. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30184. };
  30185. /**
  30186. * Creates a dashed line mesh.
  30187. * Please consider using the same method from the MeshBuilder class instead.
  30188. * 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.
  30189. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30190. * The parameter `points` is an array successive Vector3.
  30191. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30192. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30193. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30194. * 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
  30195. * When updating an instance, remember that only point positions can change, not the number of points.
  30196. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30197. */
  30198. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30199. if (scene === void 0) { scene = null; }
  30200. var options = {
  30201. points: points,
  30202. dashSize: dashSize,
  30203. gapSize: gapSize,
  30204. dashNb: dashNb,
  30205. updatable: updatable,
  30206. instance: instance
  30207. };
  30208. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30209. };
  30210. /**
  30211. * Creates a polygon mesh.
  30212. * Please consider using the same method from the MeshBuilder class instead.
  30213. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30214. * 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.
  30215. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30216. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30217. * Remember you can only change the shape positions, not their number when updating a polygon.
  30218. */
  30219. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30220. var options = {
  30221. shape: shape,
  30222. holes: holes,
  30223. updatable: updatable,
  30224. sideOrientation: sideOrientation
  30225. };
  30226. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30227. };
  30228. /**
  30229. * Creates an extruded polygon mesh, with depth in the Y direction.
  30230. * Please consider using the same method from the MeshBuilder class instead.
  30231. */
  30232. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30233. var options = {
  30234. shape: shape,
  30235. holes: holes,
  30236. depth: depth,
  30237. updatable: updatable,
  30238. sideOrientation: sideOrientation
  30239. };
  30240. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30241. };
  30242. /**
  30243. * Creates an extruded shape mesh.
  30244. * 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.
  30245. * Please consider using the same method from the MeshBuilder class instead.
  30246. *
  30247. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30248. * 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
  30249. * extruded along the Z axis.
  30250. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30251. * 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.
  30252. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30253. * 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
  30254. * 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
  30255. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30256. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30257. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30258. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30259. */
  30260. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30261. if (scene === void 0) { scene = null; }
  30262. var options = {
  30263. shape: shape,
  30264. path: path,
  30265. scale: scale,
  30266. rotation: rotation,
  30267. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30268. sideOrientation: sideOrientation,
  30269. instance: instance,
  30270. updatable: updatable
  30271. };
  30272. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30273. };
  30274. /**
  30275. * Creates an custom extruded shape mesh.
  30276. * 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.
  30277. * Please consider using the same method from the MeshBuilder class instead.
  30278. *
  30279. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30280. * 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
  30281. * extruded along the Z axis.
  30282. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30283. * 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
  30284. * and the distance of this point from the begining of the path :
  30285. * ```javascript
  30286. * var rotationFunction = function(i, distance) {
  30287. * // do things
  30288. * return rotationValue; }
  30289. * ```
  30290. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30291. * 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
  30292. * and the distance of this point from the begining of the path :
  30293. * ```javascript
  30294. * var scaleFunction = function(i, distance) {
  30295. * // do things
  30296. * return scaleValue;}
  30297. * ```
  30298. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30299. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30300. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30301. * 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
  30302. * 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
  30303. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30304. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30305. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30306. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30307. */
  30308. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30309. var options = {
  30310. shape: shape,
  30311. path: path,
  30312. scaleFunction: scaleFunction,
  30313. rotationFunction: rotationFunction,
  30314. ribbonCloseArray: ribbonCloseArray,
  30315. ribbonClosePath: ribbonClosePath,
  30316. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30317. sideOrientation: sideOrientation,
  30318. instance: instance,
  30319. updatable: updatable
  30320. };
  30321. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30322. };
  30323. /**
  30324. * Creates lathe mesh.
  30325. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30326. * Please consider using the same method from the MeshBuilder class instead.
  30327. * 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
  30328. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30329. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30330. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30331. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30332. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30333. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30334. */
  30335. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30336. var options = {
  30337. shape: shape,
  30338. radius: radius,
  30339. tessellation: tessellation,
  30340. sideOrientation: sideOrientation,
  30341. updatable: updatable
  30342. };
  30343. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30344. };
  30345. /**
  30346. * Creates a plane mesh.
  30347. * Please consider using the same method from the MeshBuilder class instead.
  30348. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30349. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30350. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30351. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30352. */
  30353. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30354. var options = {
  30355. size: size,
  30356. width: size,
  30357. height: size,
  30358. sideOrientation: sideOrientation,
  30359. updatable: updatable
  30360. };
  30361. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30362. };
  30363. /**
  30364. * Creates a ground mesh.
  30365. * Please consider using the same method from the MeshBuilder class instead.
  30366. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30367. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30368. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30369. */
  30370. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30371. var options = {
  30372. width: width,
  30373. height: height,
  30374. subdivisions: subdivisions,
  30375. updatable: updatable
  30376. };
  30377. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30378. };
  30379. /**
  30380. * Creates a tiled ground mesh.
  30381. * Please consider using the same method from the MeshBuilder class instead.
  30382. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30383. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30384. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30385. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30386. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30387. * numbers of subdivisions on the ground width and height of each tile.
  30388. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30389. */
  30390. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30391. var options = {
  30392. xmin: xmin,
  30393. zmin: zmin,
  30394. xmax: xmax,
  30395. zmax: zmax,
  30396. subdivisions: subdivisions,
  30397. precision: precision,
  30398. updatable: updatable
  30399. };
  30400. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30401. };
  30402. /**
  30403. * Creates a ground mesh from a height map.
  30404. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30405. * Please consider using the same method from the MeshBuilder class instead.
  30406. * The parameter `url` sets the URL of the height map image resource.
  30407. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30408. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30409. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30410. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30411. * 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).
  30412. * This function is passed the newly built mesh :
  30413. * ```javascript
  30414. * function(mesh) { // do things
  30415. * return; }
  30416. * ```
  30417. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30418. */
  30419. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30420. var options = {
  30421. width: width,
  30422. height: height,
  30423. subdivisions: subdivisions,
  30424. minHeight: minHeight,
  30425. maxHeight: maxHeight,
  30426. updatable: updatable,
  30427. onReady: onReady
  30428. };
  30429. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30430. };
  30431. /**
  30432. * Creates a tube mesh.
  30433. * 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.
  30434. * Please consider using the same method from the MeshBuilder class instead.
  30435. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30436. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30437. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30438. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30439. * 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.
  30440. * It must return a radius value (positive float) :
  30441. * ```javascript
  30442. * var radiusFunction = function(i, distance) {
  30443. * // do things
  30444. * return radius; }
  30445. * ```
  30446. * 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
  30447. * 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
  30448. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30449. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30451. */
  30452. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30453. var options = {
  30454. path: path,
  30455. radius: radius,
  30456. tessellation: tessellation,
  30457. radiusFunction: radiusFunction,
  30458. arc: 1,
  30459. cap: cap,
  30460. updatable: updatable,
  30461. sideOrientation: sideOrientation,
  30462. instance: instance
  30463. };
  30464. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30465. };
  30466. /**
  30467. * Creates a polyhedron mesh.
  30468. * Please consider using the same method from the MeshBuilder class instead.
  30469. * 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
  30470. * to choose the wanted type.
  30471. * The parameter `size` (positive float, default 1) sets the polygon size.
  30472. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30473. * 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`.
  30474. * 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
  30475. * 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)`).
  30476. * 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
  30477. * 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.
  30478. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30479. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30480. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30481. */
  30482. Mesh.CreatePolyhedron = function (name, options, scene) {
  30483. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30484. };
  30485. /**
  30486. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30487. * Please consider using the same method from the MeshBuilder class instead.
  30488. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30489. * 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`).
  30490. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30491. * 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.
  30492. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30493. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30494. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30495. */
  30496. Mesh.CreateIcoSphere = function (name, options, scene) {
  30497. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30498. };
  30499. /**
  30500. * Creates a decal mesh.
  30501. * Please consider using the same method from the MeshBuilder class instead.
  30502. * 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.
  30503. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30504. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30505. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30506. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30507. */
  30508. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30509. var options = {
  30510. position: position,
  30511. normal: normal,
  30512. size: size,
  30513. angle: angle
  30514. };
  30515. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30516. };
  30517. // Skeletons
  30518. /**
  30519. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30520. */
  30521. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30522. if (!this._sourcePositions) {
  30523. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30524. if (!source) {
  30525. return this._sourcePositions;
  30526. }
  30527. this._sourcePositions = new Float32Array(source);
  30528. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30529. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30530. }
  30531. }
  30532. return this._sourcePositions;
  30533. };
  30534. /**
  30535. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30536. */
  30537. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30538. if (!this._sourceNormals) {
  30539. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30540. if (!source) {
  30541. return this._sourceNormals;
  30542. }
  30543. this._sourceNormals = new Float32Array(source);
  30544. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30545. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30546. }
  30547. }
  30548. return this._sourceNormals;
  30549. };
  30550. /**
  30551. * Updates the vertex buffer by applying transformation from the bones.
  30552. * Returns the Mesh.
  30553. *
  30554. * @param {skeleton} skeleton to apply
  30555. */
  30556. Mesh.prototype.applySkeleton = function (skeleton) {
  30557. if (!this.geometry) {
  30558. return this;
  30559. }
  30560. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30561. return this;
  30562. }
  30563. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30564. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30565. return this;
  30566. }
  30567. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30568. return this;
  30569. }
  30570. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30571. return this;
  30572. }
  30573. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30574. return this;
  30575. }
  30576. if (!this._sourcePositions) {
  30577. var submeshes = this.subMeshes.slice();
  30578. this.setPositionsForCPUSkinning();
  30579. this.subMeshes = submeshes;
  30580. }
  30581. if (!this._sourceNormals) {
  30582. this.setNormalsForCPUSkinning();
  30583. }
  30584. // positionsData checks for not being Float32Array will only pass at most once
  30585. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30586. if (!positionsData) {
  30587. return this;
  30588. }
  30589. if (!(positionsData instanceof Float32Array)) {
  30590. positionsData = new Float32Array(positionsData);
  30591. }
  30592. // normalsData checks for not being Float32Array will only pass at most once
  30593. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30594. if (!normalsData) {
  30595. return this;
  30596. }
  30597. if (!(normalsData instanceof Float32Array)) {
  30598. normalsData = new Float32Array(normalsData);
  30599. }
  30600. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30601. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30602. if (!matricesWeightsData || !matricesIndicesData) {
  30603. return this;
  30604. }
  30605. var needExtras = this.numBoneInfluencers > 4;
  30606. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30607. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30608. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30609. var tempVector3 = BABYLON.Vector3.Zero();
  30610. var finalMatrix = new BABYLON.Matrix();
  30611. var tempMatrix = new BABYLON.Matrix();
  30612. var matWeightIdx = 0;
  30613. var inf;
  30614. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30615. var weight;
  30616. for (inf = 0; inf < 4; inf++) {
  30617. weight = matricesWeightsData[matWeightIdx + inf];
  30618. if (weight > 0) {
  30619. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30620. finalMatrix.addToSelf(tempMatrix);
  30621. }
  30622. else
  30623. break;
  30624. }
  30625. if (needExtras) {
  30626. for (inf = 0; inf < 4; inf++) {
  30627. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30628. if (weight > 0) {
  30629. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30630. finalMatrix.addToSelf(tempMatrix);
  30631. }
  30632. else
  30633. break;
  30634. }
  30635. }
  30636. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30637. tempVector3.toArray(positionsData, index);
  30638. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30639. tempVector3.toArray(normalsData, index);
  30640. finalMatrix.reset();
  30641. }
  30642. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30643. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30644. return this;
  30645. };
  30646. // Tools
  30647. /**
  30648. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30649. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30650. */
  30651. Mesh.MinMax = function (meshes) {
  30652. var minVector = null;
  30653. var maxVector = null;
  30654. meshes.forEach(function (mesh, index, array) {
  30655. var boundingInfo = mesh.getBoundingInfo();
  30656. var boundingBox = boundingInfo.boundingBox;
  30657. if (!minVector || !maxVector) {
  30658. minVector = boundingBox.minimumWorld;
  30659. maxVector = boundingBox.maximumWorld;
  30660. }
  30661. else {
  30662. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30663. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30664. }
  30665. });
  30666. if (!minVector || !maxVector) {
  30667. return {
  30668. min: BABYLON.Vector3.Zero(),
  30669. max: BABYLON.Vector3.Zero()
  30670. };
  30671. }
  30672. return {
  30673. min: minVector,
  30674. max: maxVector
  30675. };
  30676. };
  30677. /**
  30678. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30679. */
  30680. Mesh.Center = function (meshesOrMinMaxVector) {
  30681. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30682. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30683. };
  30684. /**
  30685. * Merge the array of meshes into a single mesh for performance reasons.
  30686. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30687. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30688. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30689. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30690. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30691. */
  30692. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30693. if (disposeSource === void 0) { disposeSource = true; }
  30694. var index;
  30695. if (!allow32BitsIndices) {
  30696. var totalVertices = 0;
  30697. // Counting vertices
  30698. for (index = 0; index < meshes.length; index++) {
  30699. if (meshes[index]) {
  30700. totalVertices += meshes[index].getTotalVertices();
  30701. if (totalVertices > 65536) {
  30702. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30703. return null;
  30704. }
  30705. }
  30706. }
  30707. }
  30708. // Merge
  30709. var vertexData = null;
  30710. var otherVertexData;
  30711. var indiceArray = new Array();
  30712. var source = null;
  30713. for (index = 0; index < meshes.length; index++) {
  30714. if (meshes[index]) {
  30715. meshes[index].computeWorldMatrix(true);
  30716. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30717. otherVertexData.transform(meshes[index].getWorldMatrix());
  30718. if (vertexData) {
  30719. vertexData.merge(otherVertexData);
  30720. }
  30721. else {
  30722. vertexData = otherVertexData;
  30723. source = meshes[index];
  30724. }
  30725. if (subdivideWithSubMeshes) {
  30726. indiceArray.push(meshes[index].getTotalIndices());
  30727. }
  30728. }
  30729. }
  30730. source = source;
  30731. if (!meshSubclass) {
  30732. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30733. }
  30734. vertexData.applyToMesh(meshSubclass);
  30735. // Setting properties
  30736. meshSubclass.material = source.material;
  30737. meshSubclass.checkCollisions = source.checkCollisions;
  30738. // Cleaning
  30739. if (disposeSource) {
  30740. for (index = 0; index < meshes.length; index++) {
  30741. if (meshes[index]) {
  30742. meshes[index].dispose();
  30743. }
  30744. }
  30745. }
  30746. // Subdivide
  30747. if (subdivideWithSubMeshes) {
  30748. //-- Suppresions du submesh global
  30749. meshSubclass.releaseSubMeshes();
  30750. index = 0;
  30751. var offset = 0;
  30752. //-- aplique la subdivision en fonction du tableau d'indices
  30753. while (index < indiceArray.length) {
  30754. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30755. offset += indiceArray[index];
  30756. index++;
  30757. }
  30758. }
  30759. return meshSubclass;
  30760. };
  30761. // Consts
  30762. Mesh._FRONTSIDE = 0;
  30763. Mesh._BACKSIDE = 1;
  30764. Mesh._DOUBLESIDE = 2;
  30765. Mesh._DEFAULTSIDE = 0;
  30766. Mesh._NO_CAP = 0;
  30767. Mesh._CAP_START = 1;
  30768. Mesh._CAP_END = 2;
  30769. Mesh._CAP_ALL = 3;
  30770. return Mesh;
  30771. }(BABYLON.AbstractMesh));
  30772. BABYLON.Mesh = Mesh;
  30773. })(BABYLON || (BABYLON = {}));
  30774. //# sourceMappingURL=babylon.mesh.js.map
  30775. "use strict";
  30776. var BABYLON;
  30777. (function (BABYLON) {
  30778. var BaseSubMesh = /** @class */ (function () {
  30779. function BaseSubMesh() {
  30780. }
  30781. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30782. get: function () {
  30783. return this._materialEffect;
  30784. },
  30785. enumerable: true,
  30786. configurable: true
  30787. });
  30788. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30789. if (defines === void 0) { defines = null; }
  30790. if (this._materialEffect === effect) {
  30791. if (!effect) {
  30792. this._materialDefines = null;
  30793. }
  30794. return;
  30795. }
  30796. this._materialDefines = defines;
  30797. this._materialEffect = effect;
  30798. };
  30799. return BaseSubMesh;
  30800. }());
  30801. BABYLON.BaseSubMesh = BaseSubMesh;
  30802. var SubMesh = /** @class */ (function (_super) {
  30803. __extends(SubMesh, _super);
  30804. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30805. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30806. var _this = _super.call(this) || this;
  30807. _this.materialIndex = materialIndex;
  30808. _this.verticesStart = verticesStart;
  30809. _this.verticesCount = verticesCount;
  30810. _this.indexStart = indexStart;
  30811. _this.indexCount = indexCount;
  30812. _this._renderId = 0;
  30813. _this._mesh = mesh;
  30814. _this._renderingMesh = renderingMesh || mesh;
  30815. mesh.subMeshes.push(_this);
  30816. _this._trianglePlanes = [];
  30817. _this._id = mesh.subMeshes.length - 1;
  30818. if (createBoundingBox) {
  30819. _this.refreshBoundingInfo();
  30820. mesh.computeWorldMatrix(true);
  30821. }
  30822. return _this;
  30823. }
  30824. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30825. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30826. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30827. };
  30828. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30829. get: function () {
  30830. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30831. },
  30832. enumerable: true,
  30833. configurable: true
  30834. });
  30835. /**
  30836. * Returns the submesh BoudingInfo object.
  30837. */
  30838. SubMesh.prototype.getBoundingInfo = function () {
  30839. if (this.IsGlobal) {
  30840. return this._mesh.getBoundingInfo();
  30841. }
  30842. return this._boundingInfo;
  30843. };
  30844. /**
  30845. * Sets the submesh BoundingInfo.
  30846. * Return the SubMesh.
  30847. */
  30848. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30849. this._boundingInfo = boundingInfo;
  30850. return this;
  30851. };
  30852. /**
  30853. * Returns the mesh of the current submesh.
  30854. */
  30855. SubMesh.prototype.getMesh = function () {
  30856. return this._mesh;
  30857. };
  30858. /**
  30859. * Returns the rendering mesh of the submesh.
  30860. */
  30861. SubMesh.prototype.getRenderingMesh = function () {
  30862. return this._renderingMesh;
  30863. };
  30864. /**
  30865. * Returns the submesh material.
  30866. */
  30867. SubMesh.prototype.getMaterial = function () {
  30868. var rootMaterial = this._renderingMesh.material;
  30869. if (rootMaterial === null || rootMaterial === undefined) {
  30870. return this._mesh.getScene().defaultMaterial;
  30871. }
  30872. else if (rootMaterial.getSubMaterial) {
  30873. var multiMaterial = rootMaterial;
  30874. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30875. if (this._currentMaterial !== effectiveMaterial) {
  30876. this._currentMaterial = effectiveMaterial;
  30877. this._materialDefines = null;
  30878. }
  30879. return effectiveMaterial;
  30880. }
  30881. return rootMaterial;
  30882. };
  30883. // Methods
  30884. /**
  30885. * Sets a new updated BoundingInfo object to the submesh.
  30886. * Returns the SubMesh.
  30887. */
  30888. SubMesh.prototype.refreshBoundingInfo = function () {
  30889. this._lastColliderWorldVertices = null;
  30890. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30891. return this;
  30892. }
  30893. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30894. if (!data) {
  30895. this._boundingInfo = this._mesh.getBoundingInfo();
  30896. return this;
  30897. }
  30898. var indices = this._renderingMesh.getIndices();
  30899. var extend;
  30900. //is this the only submesh?
  30901. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30902. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30903. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30904. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30905. }
  30906. else {
  30907. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30908. }
  30909. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30910. return this;
  30911. };
  30912. SubMesh.prototype._checkCollision = function (collider) {
  30913. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30914. return boundingInfo._checkCollision(collider);
  30915. };
  30916. /**
  30917. * Updates the submesh BoundingInfo.
  30918. * Returns the Submesh.
  30919. */
  30920. SubMesh.prototype.updateBoundingInfo = function (world) {
  30921. var boundingInfo = this.getBoundingInfo();
  30922. if (!boundingInfo) {
  30923. this.refreshBoundingInfo();
  30924. boundingInfo = this.getBoundingInfo();
  30925. }
  30926. boundingInfo.update(world);
  30927. return this;
  30928. };
  30929. /**
  30930. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30931. * Boolean returned.
  30932. */
  30933. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30934. var boundingInfo = this.getBoundingInfo();
  30935. if (!boundingInfo) {
  30936. return false;
  30937. }
  30938. return boundingInfo.isInFrustum(frustumPlanes);
  30939. };
  30940. /**
  30941. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30942. * Boolean returned.
  30943. */
  30944. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30945. var boundingInfo = this.getBoundingInfo();
  30946. if (!boundingInfo) {
  30947. return false;
  30948. }
  30949. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30950. };
  30951. /**
  30952. * Renders the submesh.
  30953. * Returns it.
  30954. */
  30955. SubMesh.prototype.render = function (enableAlphaMode) {
  30956. this._renderingMesh.render(this, enableAlphaMode);
  30957. return this;
  30958. };
  30959. /**
  30960. * Returns a new Index Buffer.
  30961. * Type returned : WebGLBuffer.
  30962. */
  30963. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30964. if (!this._linesIndexBuffer) {
  30965. var linesIndices = [];
  30966. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30967. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30968. }
  30969. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30970. this.linesIndexCount = linesIndices.length;
  30971. }
  30972. return this._linesIndexBuffer;
  30973. };
  30974. /**
  30975. * True is the passed Ray intersects the submesh bounding box.
  30976. * Boolean returned.
  30977. */
  30978. SubMesh.prototype.canIntersects = function (ray) {
  30979. var boundingInfo = this.getBoundingInfo();
  30980. if (!boundingInfo) {
  30981. return false;
  30982. }
  30983. return ray.intersectsBox(boundingInfo.boundingBox);
  30984. };
  30985. /**
  30986. * Returns an object IntersectionInfo.
  30987. */
  30988. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30989. var intersectInfo = null;
  30990. var material = this.getMaterial();
  30991. if (!material) {
  30992. return null;
  30993. }
  30994. switch (material.fillMode) {
  30995. case BABYLON.Material.PointListDrawMode:
  30996. case BABYLON.Material.LineListDrawMode:
  30997. case BABYLON.Material.LineLoopDrawMode:
  30998. case BABYLON.Material.LineStripDrawMode:
  30999. case BABYLON.Material.TriangleFanDrawMode:
  31000. case BABYLON.Material.TriangleStripDrawMode:
  31001. return null;
  31002. }
  31003. // LineMesh first as it's also a Mesh...
  31004. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31005. var lineMesh = this._mesh;
  31006. // Line test
  31007. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31008. var p0 = positions[indices[index]];
  31009. var p1 = positions[indices[index + 1]];
  31010. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31011. if (length < 0) {
  31012. continue;
  31013. }
  31014. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31015. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31016. if (fastCheck) {
  31017. break;
  31018. }
  31019. }
  31020. }
  31021. }
  31022. else {
  31023. // Triangles test
  31024. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31025. var p0 = positions[indices[index]];
  31026. var p1 = positions[indices[index + 1]];
  31027. var p2 = positions[indices[index + 2]];
  31028. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31029. if (currentIntersectInfo) {
  31030. if (currentIntersectInfo.distance < 0) {
  31031. continue;
  31032. }
  31033. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31034. intersectInfo = currentIntersectInfo;
  31035. intersectInfo.faceId = index / 3;
  31036. if (fastCheck) {
  31037. break;
  31038. }
  31039. }
  31040. }
  31041. }
  31042. }
  31043. return intersectInfo;
  31044. };
  31045. SubMesh.prototype._rebuild = function () {
  31046. if (this._linesIndexBuffer) {
  31047. this._linesIndexBuffer = null;
  31048. }
  31049. };
  31050. // Clone
  31051. /**
  31052. * Creates a new Submesh from the passed Mesh.
  31053. */
  31054. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31055. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31056. if (!this.IsGlobal) {
  31057. var boundingInfo = this.getBoundingInfo();
  31058. if (!boundingInfo) {
  31059. return result;
  31060. }
  31061. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31062. }
  31063. return result;
  31064. };
  31065. // Dispose
  31066. /**
  31067. * Disposes the Submesh.
  31068. * Returns nothing.
  31069. */
  31070. SubMesh.prototype.dispose = function () {
  31071. if (this._linesIndexBuffer) {
  31072. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31073. this._linesIndexBuffer = null;
  31074. }
  31075. // Remove from mesh
  31076. var index = this._mesh.subMeshes.indexOf(this);
  31077. this._mesh.subMeshes.splice(index, 1);
  31078. };
  31079. // Statics
  31080. /**
  31081. * Creates a new Submesh from the passed parameters :
  31082. * - materialIndex (integer) : the index of the main mesh material.
  31083. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31084. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31085. * - mesh (Mesh) : the main mesh to create the submesh from.
  31086. * - renderingMesh (optional Mesh) : rendering mesh.
  31087. */
  31088. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31089. var minVertexIndex = Number.MAX_VALUE;
  31090. var maxVertexIndex = -Number.MAX_VALUE;
  31091. renderingMesh = (renderingMesh || mesh);
  31092. var indices = renderingMesh.getIndices();
  31093. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31094. var vertexIndex = indices[index];
  31095. if (vertexIndex < minVertexIndex)
  31096. minVertexIndex = vertexIndex;
  31097. if (vertexIndex > maxVertexIndex)
  31098. maxVertexIndex = vertexIndex;
  31099. }
  31100. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31101. };
  31102. return SubMesh;
  31103. }(BaseSubMesh));
  31104. BABYLON.SubMesh = SubMesh;
  31105. })(BABYLON || (BABYLON = {}));
  31106. //# sourceMappingURL=babylon.subMesh.js.map
  31107. "use strict";
  31108. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31109. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31110. s = arguments[i];
  31111. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31112. t[p] = s[p];
  31113. }
  31114. return t;
  31115. };
  31116. var BABYLON;
  31117. (function (BABYLON) {
  31118. /**
  31119. * Manages the defines for the Material.
  31120. */
  31121. var MaterialDefines = /** @class */ (function () {
  31122. function MaterialDefines() {
  31123. this._isDirty = true;
  31124. this._areLightsDirty = true;
  31125. this._areAttributesDirty = true;
  31126. this._areTexturesDirty = true;
  31127. this._areFresnelDirty = true;
  31128. this._areMiscDirty = true;
  31129. this._areImageProcessingDirty = true;
  31130. this._normals = false;
  31131. this._uvs = false;
  31132. this._needNormals = false;
  31133. this._needUVs = false;
  31134. }
  31135. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31136. /**
  31137. * Specifies if the material needs to be re-calculated.
  31138. */
  31139. get: function () {
  31140. return this._isDirty;
  31141. },
  31142. enumerable: true,
  31143. configurable: true
  31144. });
  31145. /**
  31146. * Marks the material to indicate that it has been re-calculated.
  31147. */
  31148. MaterialDefines.prototype.markAsProcessed = function () {
  31149. this._isDirty = false;
  31150. this._areAttributesDirty = false;
  31151. this._areTexturesDirty = false;
  31152. this._areFresnelDirty = false;
  31153. this._areLightsDirty = false;
  31154. this._areMiscDirty = false;
  31155. this._areImageProcessingDirty = false;
  31156. };
  31157. /**
  31158. * Marks the material to indicate that it needs to be re-calculated.
  31159. */
  31160. MaterialDefines.prototype.markAsUnprocessed = function () {
  31161. this._isDirty = true;
  31162. };
  31163. /**
  31164. * Marks the material to indicate all of its defines need to be re-calculated.
  31165. */
  31166. MaterialDefines.prototype.markAllAsDirty = function () {
  31167. this._areTexturesDirty = true;
  31168. this._areAttributesDirty = true;
  31169. this._areLightsDirty = true;
  31170. this._areFresnelDirty = true;
  31171. this._areMiscDirty = true;
  31172. this._areImageProcessingDirty = true;
  31173. this._isDirty = true;
  31174. };
  31175. /**
  31176. * Marks the material to indicate that image processing needs to be re-calculated.
  31177. */
  31178. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31179. this._areImageProcessingDirty = true;
  31180. this._isDirty = true;
  31181. };
  31182. /**
  31183. * Marks the material to indicate the lights need to be re-calculated.
  31184. */
  31185. MaterialDefines.prototype.markAsLightDirty = function () {
  31186. this._areLightsDirty = true;
  31187. this._isDirty = true;
  31188. };
  31189. /**
  31190. * Marks the attribute state as changed.
  31191. */
  31192. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31193. this._areAttributesDirty = true;
  31194. this._isDirty = true;
  31195. };
  31196. /**
  31197. * Marks the texture state as changed.
  31198. */
  31199. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31200. this._areTexturesDirty = true;
  31201. this._isDirty = true;
  31202. };
  31203. /**
  31204. * Marks the fresnel state as changed.
  31205. */
  31206. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31207. this._areFresnelDirty = true;
  31208. this._isDirty = true;
  31209. };
  31210. /**
  31211. * Marks the misc state as changed.
  31212. */
  31213. MaterialDefines.prototype.markAsMiscDirty = function () {
  31214. this._areMiscDirty = true;
  31215. this._isDirty = true;
  31216. };
  31217. /**
  31218. * Rebuilds the material defines.
  31219. */
  31220. MaterialDefines.prototype.rebuild = function () {
  31221. if (this._keys) {
  31222. delete this._keys;
  31223. }
  31224. this._keys = [];
  31225. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31226. var key = _a[_i];
  31227. if (key[0] === "_") {
  31228. continue;
  31229. }
  31230. this._keys.push(key);
  31231. }
  31232. };
  31233. /**
  31234. * Specifies if two material defines are equal.
  31235. * @param other - A material define instance to compare to.
  31236. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31237. */
  31238. MaterialDefines.prototype.isEqual = function (other) {
  31239. if (this._keys.length !== other._keys.length) {
  31240. return false;
  31241. }
  31242. for (var index = 0; index < this._keys.length; index++) {
  31243. var prop = this._keys[index];
  31244. if (this[prop] !== other[prop]) {
  31245. return false;
  31246. }
  31247. }
  31248. return true;
  31249. };
  31250. /**
  31251. * Clones this instance's defines to another instance.
  31252. * @param other - material defines to clone values to.
  31253. */
  31254. MaterialDefines.prototype.cloneTo = function (other) {
  31255. if (this._keys.length !== other._keys.length) {
  31256. other._keys = this._keys.slice(0);
  31257. }
  31258. for (var index = 0; index < this._keys.length; index++) {
  31259. var prop = this._keys[index];
  31260. other[prop] = this[prop];
  31261. }
  31262. };
  31263. /**
  31264. * Resets the material define values.
  31265. */
  31266. MaterialDefines.prototype.reset = function () {
  31267. for (var index = 0; index < this._keys.length; index++) {
  31268. var prop = this._keys[index];
  31269. var type = typeof this[prop];
  31270. switch (type) {
  31271. case "number":
  31272. this[prop] = 0;
  31273. break;
  31274. case "string":
  31275. this[prop] = "";
  31276. break;
  31277. default:
  31278. this[prop] = false;
  31279. break;
  31280. }
  31281. }
  31282. };
  31283. /**
  31284. * Converts the material define values to a string.
  31285. * @returns - String of material define information.
  31286. */
  31287. MaterialDefines.prototype.toString = function () {
  31288. var result = "";
  31289. for (var index = 0; index < this._keys.length; index++) {
  31290. var prop = this._keys[index];
  31291. var value = this[prop];
  31292. var type = typeof value;
  31293. switch (type) {
  31294. case "number":
  31295. case "string":
  31296. result += "#define " + prop + " " + value + "\n";
  31297. break;
  31298. default:
  31299. if (value) {
  31300. result += "#define " + prop + "\n";
  31301. }
  31302. break;
  31303. }
  31304. }
  31305. return result;
  31306. };
  31307. return MaterialDefines;
  31308. }());
  31309. BABYLON.MaterialDefines = MaterialDefines;
  31310. /**
  31311. * This offers the main features of a material in BJS.
  31312. */
  31313. var Material = /** @class */ (function () {
  31314. /**
  31315. * Creates a material instance.
  31316. * @param name - The name of the material.
  31317. * @param scene - The BJS scene to reference.
  31318. * @param doNotAdd - Specifies if the material should be added to the scene.
  31319. */
  31320. function Material(name, scene, doNotAdd) {
  31321. /**
  31322. * Specifies if the ready state should be checked on each call.
  31323. */
  31324. this.checkReadyOnEveryCall = false;
  31325. /**
  31326. * Specifies if the ready state should be checked once.
  31327. */
  31328. this.checkReadyOnlyOnce = false;
  31329. /**
  31330. * The state of the material.
  31331. */
  31332. this.state = "";
  31333. /**
  31334. * The alpha value of the material.
  31335. */
  31336. this._alpha = 1.0;
  31337. /**
  31338. * Specifies if back face culling is enabled.
  31339. */
  31340. this._backFaceCulling = true;
  31341. /**
  31342. * Specifies if the material should be serialized.
  31343. */
  31344. this.doNotSerialize = false;
  31345. /**
  31346. * Specifies if the effect should be stored on sub meshes.
  31347. */
  31348. this.storeEffectOnSubMeshes = false;
  31349. /**
  31350. * An event triggered when the material is disposed.
  31351. * @type {BABYLON.Observable}
  31352. */
  31353. this.onDisposeObservable = new BABYLON.Observable();
  31354. /**
  31355. * An event triggered when the material is bound.
  31356. * @type {BABYLON.Observable}
  31357. */
  31358. this.onBindObservable = new BABYLON.Observable();
  31359. /**
  31360. * An event triggered when the material is unbound.
  31361. * @type {BABYLON.Observable}
  31362. */
  31363. this.onUnBindObservable = new BABYLON.Observable();
  31364. /**
  31365. * Stores the value of the alpha mode.
  31366. */
  31367. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31368. /**
  31369. * Stores the state of the need depth pre-pass value.
  31370. */
  31371. this._needDepthPrePass = false;
  31372. /**
  31373. * Specifies if depth writing should be disabled.
  31374. */
  31375. this.disableDepthWrite = false;
  31376. /**
  31377. * Specifies if depth writing should be forced.
  31378. */
  31379. this.forceDepthWrite = false;
  31380. /**
  31381. * Specifies if there should be a separate pass for culling.
  31382. */
  31383. this.separateCullingPass = false;
  31384. /**
  31385. * Stores the state specifing if fog should be enabled.
  31386. */
  31387. this._fogEnabled = true;
  31388. /**
  31389. * Stores the size of points.
  31390. */
  31391. this.pointSize = 1.0;
  31392. /**
  31393. * Stores the z offset value.
  31394. */
  31395. this.zOffset = 0;
  31396. /**
  31397. * Specifies if the material was previously ready.
  31398. */
  31399. this._wasPreviouslyReady = false;
  31400. /**
  31401. * Stores the fill mode state.
  31402. */
  31403. this._fillMode = Material.TriangleFillMode;
  31404. this.name = name;
  31405. this.id = name || BABYLON.Tools.RandomId();
  31406. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31407. if (this._scene.useRightHandedSystem) {
  31408. this.sideOrientation = Material.ClockWiseSideOrientation;
  31409. }
  31410. else {
  31411. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31412. }
  31413. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31414. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31415. if (!doNotAdd) {
  31416. this._scene.materials.push(this);
  31417. }
  31418. }
  31419. Object.defineProperty(Material, "TriangleFillMode", {
  31420. /**
  31421. * Returns the triangle fill mode.
  31422. */
  31423. get: function () {
  31424. return Material._TriangleFillMode;
  31425. },
  31426. enumerable: true,
  31427. configurable: true
  31428. });
  31429. Object.defineProperty(Material, "WireFrameFillMode", {
  31430. /**
  31431. * Returns the wireframe mode.
  31432. */
  31433. get: function () {
  31434. return Material._WireFrameFillMode;
  31435. },
  31436. enumerable: true,
  31437. configurable: true
  31438. });
  31439. Object.defineProperty(Material, "PointFillMode", {
  31440. /**
  31441. * Returns the point fill mode.
  31442. */
  31443. get: function () {
  31444. return Material._PointFillMode;
  31445. },
  31446. enumerable: true,
  31447. configurable: true
  31448. });
  31449. Object.defineProperty(Material, "PointListDrawMode", {
  31450. /**
  31451. * Returns the point list draw mode.
  31452. */
  31453. get: function () {
  31454. return Material._PointListDrawMode;
  31455. },
  31456. enumerable: true,
  31457. configurable: true
  31458. });
  31459. Object.defineProperty(Material, "LineListDrawMode", {
  31460. /**
  31461. * Returns the line list draw mode.
  31462. */
  31463. get: function () {
  31464. return Material._LineListDrawMode;
  31465. },
  31466. enumerable: true,
  31467. configurable: true
  31468. });
  31469. Object.defineProperty(Material, "LineLoopDrawMode", {
  31470. /**
  31471. * Returns the line loop draw mode.
  31472. */
  31473. get: function () {
  31474. return Material._LineLoopDrawMode;
  31475. },
  31476. enumerable: true,
  31477. configurable: true
  31478. });
  31479. Object.defineProperty(Material, "LineStripDrawMode", {
  31480. /**
  31481. * Returns the line strip draw mode.
  31482. */
  31483. get: function () {
  31484. return Material._LineStripDrawMode;
  31485. },
  31486. enumerable: true,
  31487. configurable: true
  31488. });
  31489. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31490. /**
  31491. * Returns the triangle strip draw mode.
  31492. */
  31493. get: function () {
  31494. return Material._TriangleStripDrawMode;
  31495. },
  31496. enumerable: true,
  31497. configurable: true
  31498. });
  31499. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31500. /**
  31501. * Returns the triangle fan draw mode.
  31502. */
  31503. get: function () {
  31504. return Material._TriangleFanDrawMode;
  31505. },
  31506. enumerable: true,
  31507. configurable: true
  31508. });
  31509. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31510. /**
  31511. * Returns the clock-wise side orientation.
  31512. */
  31513. get: function () {
  31514. return Material._ClockWiseSideOrientation;
  31515. },
  31516. enumerable: true,
  31517. configurable: true
  31518. });
  31519. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31520. /**
  31521. * Returns the counter clock-wise side orientation.
  31522. */
  31523. get: function () {
  31524. return Material._CounterClockWiseSideOrientation;
  31525. },
  31526. enumerable: true,
  31527. configurable: true
  31528. });
  31529. Object.defineProperty(Material, "TextureDirtyFlag", {
  31530. /**
  31531. * Returns the dirty texture flag value.
  31532. */
  31533. get: function () {
  31534. return Material._TextureDirtyFlag;
  31535. },
  31536. enumerable: true,
  31537. configurable: true
  31538. });
  31539. Object.defineProperty(Material, "LightDirtyFlag", {
  31540. /**
  31541. * Returns the dirty light flag value.
  31542. */
  31543. get: function () {
  31544. return Material._LightDirtyFlag;
  31545. },
  31546. enumerable: true,
  31547. configurable: true
  31548. });
  31549. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31550. /**
  31551. * Returns the dirty fresnel flag value.
  31552. */
  31553. get: function () {
  31554. return Material._FresnelDirtyFlag;
  31555. },
  31556. enumerable: true,
  31557. configurable: true
  31558. });
  31559. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31560. /**
  31561. * Returns the dirty attributes flag value.
  31562. */
  31563. get: function () {
  31564. return Material._AttributesDirtyFlag;
  31565. },
  31566. enumerable: true,
  31567. configurable: true
  31568. });
  31569. Object.defineProperty(Material, "MiscDirtyFlag", {
  31570. /**
  31571. * Returns the dirty misc flag value.
  31572. */
  31573. get: function () {
  31574. return Material._MiscDirtyFlag;
  31575. },
  31576. enumerable: true,
  31577. configurable: true
  31578. });
  31579. Object.defineProperty(Material.prototype, "alpha", {
  31580. /**
  31581. * Gets the alpha value of the material.
  31582. */
  31583. get: function () {
  31584. return this._alpha;
  31585. },
  31586. /**
  31587. * Sets the alpha value of the material.
  31588. */
  31589. set: function (value) {
  31590. if (this._alpha === value) {
  31591. return;
  31592. }
  31593. this._alpha = value;
  31594. this.markAsDirty(Material.MiscDirtyFlag);
  31595. },
  31596. enumerable: true,
  31597. configurable: true
  31598. });
  31599. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31600. /**
  31601. * Gets the back-face culling state.
  31602. */
  31603. get: function () {
  31604. return this._backFaceCulling;
  31605. },
  31606. /**
  31607. * Sets the back-face culling state.
  31608. */
  31609. set: function (value) {
  31610. if (this._backFaceCulling === value) {
  31611. return;
  31612. }
  31613. this._backFaceCulling = value;
  31614. this.markAsDirty(Material.TextureDirtyFlag);
  31615. },
  31616. enumerable: true,
  31617. configurable: true
  31618. });
  31619. Object.defineProperty(Material.prototype, "onDispose", {
  31620. /**
  31621. * Called during a dispose event.
  31622. */
  31623. set: function (callback) {
  31624. if (this._onDisposeObserver) {
  31625. this.onDisposeObservable.remove(this._onDisposeObserver);
  31626. }
  31627. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31628. },
  31629. enumerable: true,
  31630. configurable: true
  31631. });
  31632. Object.defineProperty(Material.prototype, "onBind", {
  31633. /**
  31634. * Called during a bind event.
  31635. */
  31636. set: function (callback) {
  31637. if (this._onBindObserver) {
  31638. this.onBindObservable.remove(this._onBindObserver);
  31639. }
  31640. this._onBindObserver = this.onBindObservable.add(callback);
  31641. },
  31642. enumerable: true,
  31643. configurable: true
  31644. });
  31645. Object.defineProperty(Material.prototype, "alphaMode", {
  31646. /**
  31647. * Gets the value of the alpha mode.
  31648. */
  31649. get: function () {
  31650. return this._alphaMode;
  31651. },
  31652. /**
  31653. * Sets the value of the alpha mode.
  31654. */
  31655. set: function (value) {
  31656. if (this._alphaMode === value) {
  31657. return;
  31658. }
  31659. this._alphaMode = value;
  31660. this.markAsDirty(Material.TextureDirtyFlag);
  31661. },
  31662. enumerable: true,
  31663. configurable: true
  31664. });
  31665. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31666. /**
  31667. * Gets the depth pre-pass value.
  31668. */
  31669. get: function () {
  31670. return this._needDepthPrePass;
  31671. },
  31672. /**
  31673. * Sets the need depth pre-pass value.
  31674. */
  31675. set: function (value) {
  31676. if (this._needDepthPrePass === value) {
  31677. return;
  31678. }
  31679. this._needDepthPrePass = value;
  31680. if (this._needDepthPrePass) {
  31681. this.checkReadyOnEveryCall = true;
  31682. }
  31683. },
  31684. enumerable: true,
  31685. configurable: true
  31686. });
  31687. Object.defineProperty(Material.prototype, "fogEnabled", {
  31688. /**
  31689. * Gets the value of the fog enabled state.
  31690. */
  31691. get: function () {
  31692. return this._fogEnabled;
  31693. },
  31694. /**
  31695. * Sets the state for enabling fog.
  31696. */
  31697. set: function (value) {
  31698. if (this._fogEnabled === value) {
  31699. return;
  31700. }
  31701. this._fogEnabled = value;
  31702. this.markAsDirty(Material.MiscDirtyFlag);
  31703. },
  31704. enumerable: true,
  31705. configurable: true
  31706. });
  31707. Object.defineProperty(Material.prototype, "wireframe", {
  31708. /**
  31709. * Gets a value specifying if wireframe mode is enabled.
  31710. */
  31711. get: function () {
  31712. switch (this._fillMode) {
  31713. case Material.WireFrameFillMode:
  31714. case Material.LineListDrawMode:
  31715. case Material.LineLoopDrawMode:
  31716. case Material.LineStripDrawMode:
  31717. return true;
  31718. }
  31719. return this._scene.forceWireframe;
  31720. },
  31721. /**
  31722. * Sets the state of wireframe mode.
  31723. */
  31724. set: function (value) {
  31725. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31726. },
  31727. enumerable: true,
  31728. configurable: true
  31729. });
  31730. Object.defineProperty(Material.prototype, "pointsCloud", {
  31731. /**
  31732. * Gets the value specifying if point clouds are enabled.
  31733. */
  31734. get: function () {
  31735. switch (this._fillMode) {
  31736. case Material.PointFillMode:
  31737. case Material.PointListDrawMode:
  31738. return true;
  31739. }
  31740. return this._scene.forcePointsCloud;
  31741. },
  31742. /**
  31743. * Sets the state of point cloud mode.
  31744. */
  31745. set: function (value) {
  31746. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31747. },
  31748. enumerable: true,
  31749. configurable: true
  31750. });
  31751. Object.defineProperty(Material.prototype, "fillMode", {
  31752. /**
  31753. * Gets the material fill mode.
  31754. */
  31755. get: function () {
  31756. return this._fillMode;
  31757. },
  31758. /**
  31759. * Sets the material fill mode.
  31760. */
  31761. set: function (value) {
  31762. if (this._fillMode === value) {
  31763. return;
  31764. }
  31765. this._fillMode = value;
  31766. this.markAsDirty(Material.MiscDirtyFlag);
  31767. },
  31768. enumerable: true,
  31769. configurable: true
  31770. });
  31771. /**
  31772. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31773. * subclasses should override adding information pertainent to themselves.
  31774. * @returns - String with material information.
  31775. */
  31776. Material.prototype.toString = function (fullDetails) {
  31777. var ret = "Name: " + this.name;
  31778. if (fullDetails) {
  31779. }
  31780. return ret;
  31781. };
  31782. /**
  31783. * Gets the class name of the material.
  31784. * @returns - String with the class name of the material.
  31785. */
  31786. Material.prototype.getClassName = function () {
  31787. return "Material";
  31788. };
  31789. Object.defineProperty(Material.prototype, "isFrozen", {
  31790. /**
  31791. * Specifies if updates for the material been locked.
  31792. */
  31793. get: function () {
  31794. return this.checkReadyOnlyOnce;
  31795. },
  31796. enumerable: true,
  31797. configurable: true
  31798. });
  31799. /**
  31800. * Locks updates for the material.
  31801. */
  31802. Material.prototype.freeze = function () {
  31803. this.checkReadyOnlyOnce = true;
  31804. };
  31805. /**
  31806. * Unlocks updates for the material.
  31807. */
  31808. Material.prototype.unfreeze = function () {
  31809. this.checkReadyOnlyOnce = false;
  31810. };
  31811. /**
  31812. * Specifies if the material is ready to be used.
  31813. * @param mesh - BJS mesh.
  31814. * @param useInstances - Specifies if instances should be used.
  31815. * @returns - Boolean indicating if the material is ready to be used.
  31816. */
  31817. Material.prototype.isReady = function (mesh, useInstances) {
  31818. return true;
  31819. };
  31820. /**
  31821. * Specifies that the submesh is ready to be used.
  31822. * @param mesh - BJS mesh.
  31823. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31824. * @param useInstances - Specifies that instances should be used.
  31825. * @returns - boolean indicating that the submesh is ready or not.
  31826. */
  31827. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31828. return false;
  31829. };
  31830. /**
  31831. * Returns the material effect.
  31832. * @returns - Nullable material effect.
  31833. */
  31834. Material.prototype.getEffect = function () {
  31835. return this._effect;
  31836. };
  31837. /**
  31838. * Returns the BJS scene.
  31839. * @returns - BJS Scene.
  31840. */
  31841. Material.prototype.getScene = function () {
  31842. return this._scene;
  31843. };
  31844. /**
  31845. * Specifies if the material will require alpha blending
  31846. * @returns - Boolean specifying if alpha blending is needed.
  31847. */
  31848. Material.prototype.needAlphaBlending = function () {
  31849. return (this.alpha < 1.0);
  31850. };
  31851. /**
  31852. * Specifies if the mesh will require alpha blending.
  31853. * @param mesh - BJS mesh.
  31854. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31855. */
  31856. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31857. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31858. };
  31859. /**
  31860. * Specifies if this material should be rendered in alpha test mode.
  31861. * @returns - Boolean specifying if an alpha test is needed.
  31862. */
  31863. Material.prototype.needAlphaTesting = function () {
  31864. return false;
  31865. };
  31866. /**
  31867. * Gets the texture used for the alpha test.
  31868. * @returns - Nullable alpha test texture.
  31869. */
  31870. Material.prototype.getAlphaTestTexture = function () {
  31871. return null;
  31872. };
  31873. /**
  31874. * Marks the material to indicate that it needs to be re-calculated.
  31875. */
  31876. Material.prototype.markDirty = function () {
  31877. this._wasPreviouslyReady = false;
  31878. };
  31879. Material.prototype._preBind = function (effect, overrideOrientation) {
  31880. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31881. var engine = this._scene.getEngine();
  31882. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31883. var reverse = orientation === Material.ClockWiseSideOrientation;
  31884. engine.enableEffect(effect ? effect : this._effect);
  31885. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31886. return reverse;
  31887. };
  31888. /**
  31889. * Binds the material to the mesh.
  31890. * @param world - World transformation matrix.
  31891. * @param mesh - Mesh to bind the material to.
  31892. */
  31893. Material.prototype.bind = function (world, mesh) {
  31894. };
  31895. /**
  31896. * Binds the submesh to the material.
  31897. * @param world - World transformation matrix.
  31898. * @param mesh - Mesh containing the submesh.
  31899. * @param subMesh - Submesh to bind the material to.
  31900. */
  31901. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31902. };
  31903. /**
  31904. * Binds the world matrix to the material.
  31905. * @param world - World transformation matrix.
  31906. */
  31907. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31908. };
  31909. /**
  31910. * Binds the scene's uniform buffer to the effect.
  31911. * @param effect - Effect to bind to the scene uniform buffer.
  31912. * @param sceneUbo - Scene uniform buffer.
  31913. */
  31914. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31915. sceneUbo.bindToEffect(effect, "Scene");
  31916. };
  31917. /**
  31918. * Binds the view matrix to the effect.
  31919. * @param effect - Effect to bind the view matrix to.
  31920. */
  31921. Material.prototype.bindView = function (effect) {
  31922. if (!this._useUBO) {
  31923. effect.setMatrix("view", this.getScene().getViewMatrix());
  31924. }
  31925. else {
  31926. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31927. }
  31928. };
  31929. /**
  31930. * Binds the view projection matrix to the effect.
  31931. * @param effect - Effect to bind the view projection matrix to.
  31932. */
  31933. Material.prototype.bindViewProjection = function (effect) {
  31934. if (!this._useUBO) {
  31935. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31936. }
  31937. else {
  31938. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31939. }
  31940. };
  31941. /**
  31942. * Specifies if material alpha testing should be turned on for the mesh.
  31943. * @param mesh - BJS mesh.
  31944. */
  31945. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31946. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31947. };
  31948. /**
  31949. * Processes to execute after binding the material to a mesh.
  31950. * @param mesh - BJS mesh.
  31951. */
  31952. Material.prototype._afterBind = function (mesh) {
  31953. this._scene._cachedMaterial = this;
  31954. if (mesh) {
  31955. this._scene._cachedVisibility = mesh.visibility;
  31956. }
  31957. else {
  31958. this._scene._cachedVisibility = 1;
  31959. }
  31960. if (mesh) {
  31961. this.onBindObservable.notifyObservers(mesh);
  31962. }
  31963. if (this.disableDepthWrite) {
  31964. var engine = this._scene.getEngine();
  31965. this._cachedDepthWriteState = engine.getDepthWrite();
  31966. engine.setDepthWrite(false);
  31967. }
  31968. };
  31969. /**
  31970. * Unbinds the material from the mesh.
  31971. */
  31972. Material.prototype.unbind = function () {
  31973. this.onUnBindObservable.notifyObservers(this);
  31974. if (this.disableDepthWrite) {
  31975. var engine = this._scene.getEngine();
  31976. engine.setDepthWrite(this._cachedDepthWriteState);
  31977. }
  31978. };
  31979. /**
  31980. * Gets the active textures from the material.
  31981. * @returns - Array of textures.
  31982. */
  31983. Material.prototype.getActiveTextures = function () {
  31984. return [];
  31985. };
  31986. /**
  31987. * Specifies if the material uses a texture.
  31988. * @param texture - Texture to check against the material.
  31989. * @returns - Boolean specifying if the material uses the texture.
  31990. */
  31991. Material.prototype.hasTexture = function (texture) {
  31992. return false;
  31993. };
  31994. /**
  31995. * Makes a duplicate of the material, and gives it a new name.
  31996. * @param name - Name to call the duplicated material.
  31997. * @returns - Nullable cloned material
  31998. */
  31999. Material.prototype.clone = function (name) {
  32000. return null;
  32001. };
  32002. /**
  32003. * Gets the meshes bound to the material.
  32004. * @returns - Array of meshes bound to the material.
  32005. */
  32006. Material.prototype.getBindedMeshes = function () {
  32007. var result = new Array();
  32008. for (var index = 0; index < this._scene.meshes.length; index++) {
  32009. var mesh = this._scene.meshes[index];
  32010. if (mesh.material === this) {
  32011. result.push(mesh);
  32012. }
  32013. }
  32014. return result;
  32015. };
  32016. /**
  32017. * Force shader compilation
  32018. * @param mesh - BJS mesh.
  32019. * @param onCompiled - function to execute once the material is compiled.
  32020. * @param options - options to pass to this function.
  32021. */
  32022. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32023. var _this = this;
  32024. var localOptions = __assign({ clipPlane: false }, options);
  32025. var subMesh = new BABYLON.BaseSubMesh();
  32026. var scene = this.getScene();
  32027. var checkReady = function () {
  32028. if (!_this._scene || !_this._scene.getEngine()) {
  32029. return;
  32030. }
  32031. if (subMesh._materialDefines) {
  32032. subMesh._materialDefines._renderId = -1;
  32033. }
  32034. var clipPlaneState = scene.clipPlane;
  32035. if (localOptions.clipPlane) {
  32036. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32037. }
  32038. if (_this.storeEffectOnSubMeshes) {
  32039. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32040. if (onCompiled) {
  32041. onCompiled(_this);
  32042. }
  32043. }
  32044. else {
  32045. setTimeout(checkReady, 16);
  32046. }
  32047. }
  32048. else {
  32049. if (_this.isReady(mesh)) {
  32050. if (onCompiled) {
  32051. onCompiled(_this);
  32052. }
  32053. }
  32054. else {
  32055. setTimeout(checkReady, 16);
  32056. }
  32057. }
  32058. if (localOptions.clipPlane) {
  32059. scene.clipPlane = clipPlaneState;
  32060. }
  32061. };
  32062. checkReady();
  32063. };
  32064. /**
  32065. * Force shader compilation.
  32066. * @param mesh The mesh that will use this material
  32067. * @param options Additional options for compiling the shaders
  32068. * @returns A promise that resolves when the compilation completes
  32069. */
  32070. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32071. var _this = this;
  32072. return new Promise(function (resolve) {
  32073. _this.forceCompilation(mesh, function () {
  32074. resolve();
  32075. }, options);
  32076. });
  32077. };
  32078. /**
  32079. * Marks a define in the material to indicate that it needs to be re-computed.
  32080. * @param flag - Material define flag.
  32081. */
  32082. Material.prototype.markAsDirty = function (flag) {
  32083. if (flag & Material.TextureDirtyFlag) {
  32084. this._markAllSubMeshesAsTexturesDirty();
  32085. }
  32086. if (flag & Material.LightDirtyFlag) {
  32087. this._markAllSubMeshesAsLightsDirty();
  32088. }
  32089. if (flag & Material.FresnelDirtyFlag) {
  32090. this._markAllSubMeshesAsFresnelDirty();
  32091. }
  32092. if (flag & Material.AttributesDirtyFlag) {
  32093. this._markAllSubMeshesAsAttributesDirty();
  32094. }
  32095. if (flag & Material.MiscDirtyFlag) {
  32096. this._markAllSubMeshesAsMiscDirty();
  32097. }
  32098. this.getScene().resetCachedMaterial();
  32099. };
  32100. /**
  32101. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32102. * @param func - function which checks material defines against the submeshes.
  32103. */
  32104. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32105. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32106. var mesh = _a[_i];
  32107. if (!mesh.subMeshes) {
  32108. continue;
  32109. }
  32110. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32111. var subMesh = _c[_b];
  32112. if (subMesh.getMaterial() !== this) {
  32113. continue;
  32114. }
  32115. if (!subMesh._materialDefines) {
  32116. continue;
  32117. }
  32118. func(subMesh._materialDefines);
  32119. }
  32120. }
  32121. };
  32122. /**
  32123. * Indicates that image processing needs to be re-calculated for all submeshes.
  32124. */
  32125. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32126. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32127. };
  32128. /**
  32129. * Indicates that textures need to be re-calculated for all submeshes.
  32130. */
  32131. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32132. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32133. };
  32134. /**
  32135. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32136. */
  32137. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32138. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32139. };
  32140. /**
  32141. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32142. */
  32143. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32144. this._markAllSubMeshesAsDirty(function (defines) {
  32145. defines.markAsFresnelDirty();
  32146. defines.markAsMiscDirty();
  32147. });
  32148. };
  32149. /**
  32150. * Indicates that lights need to be re-calculated for all submeshes.
  32151. */
  32152. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32153. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32154. };
  32155. /**
  32156. * Indicates that attributes need to be re-calculated for all submeshes.
  32157. */
  32158. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32159. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32160. };
  32161. /**
  32162. * Indicates that misc needs to be re-calculated for all submeshes.
  32163. */
  32164. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32165. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32166. };
  32167. /**
  32168. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32169. */
  32170. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32171. this._markAllSubMeshesAsDirty(function (defines) {
  32172. defines.markAsTexturesDirty();
  32173. defines.markAsMiscDirty();
  32174. });
  32175. };
  32176. /**
  32177. * Disposes the material.
  32178. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32179. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32180. */
  32181. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32182. // Animations
  32183. this.getScene().stopAnimation(this);
  32184. this.getScene().freeProcessedMaterials();
  32185. // Remove from scene
  32186. var index = this._scene.materials.indexOf(this);
  32187. if (index >= 0) {
  32188. this._scene.materials.splice(index, 1);
  32189. }
  32190. // Remove from meshes
  32191. for (index = 0; index < this._scene.meshes.length; index++) {
  32192. var mesh = this._scene.meshes[index];
  32193. if (mesh.material === this) {
  32194. mesh.material = null;
  32195. if (mesh.geometry) {
  32196. var geometry = (mesh.geometry);
  32197. if (this.storeEffectOnSubMeshes) {
  32198. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32199. var subMesh = _a[_i];
  32200. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32201. if (forceDisposeEffect && subMesh._materialEffect) {
  32202. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32203. }
  32204. }
  32205. }
  32206. else {
  32207. geometry._releaseVertexArrayObject(this._effect);
  32208. }
  32209. }
  32210. }
  32211. }
  32212. this._uniformBuffer.dispose();
  32213. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32214. if (forceDisposeEffect && this._effect) {
  32215. if (!this.storeEffectOnSubMeshes) {
  32216. this._scene.getEngine()._releaseEffect(this._effect);
  32217. }
  32218. this._effect = null;
  32219. }
  32220. // Callback
  32221. this.onDisposeObservable.notifyObservers(this);
  32222. this.onDisposeObservable.clear();
  32223. this.onBindObservable.clear();
  32224. this.onUnBindObservable.clear();
  32225. };
  32226. /**
  32227. * Serializes this material.
  32228. * @returns - serialized material object.
  32229. */
  32230. Material.prototype.serialize = function () {
  32231. return BABYLON.SerializationHelper.Serialize(this);
  32232. };
  32233. /**
  32234. * Creates a MultiMaterial from parse MultiMaterial data.
  32235. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32236. * @param scene - BJS scene.
  32237. * @returns - MultiMaterial.
  32238. */
  32239. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32240. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32241. multiMaterial.id = parsedMultiMaterial.id;
  32242. if (BABYLON.Tags) {
  32243. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32244. }
  32245. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32246. var subMatId = parsedMultiMaterial.materials[matIndex];
  32247. if (subMatId) {
  32248. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32249. }
  32250. else {
  32251. multiMaterial.subMaterials.push(null);
  32252. }
  32253. }
  32254. return multiMaterial;
  32255. };
  32256. /**
  32257. * Creates a material from parsed material data.
  32258. * @param parsedMaterial - Parsed material data.
  32259. * @param scene - BJS scene.
  32260. * @param rootUrl - Root URL containing the material information.
  32261. * @returns - Parsed material.
  32262. */
  32263. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32264. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32265. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32266. }
  32267. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32268. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32269. if (!BABYLON.LegacyPBRMaterial) {
  32270. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32271. return;
  32272. }
  32273. }
  32274. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32275. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32276. ;
  32277. };
  32278. // Triangle views
  32279. Material._TriangleFillMode = 0;
  32280. Material._WireFrameFillMode = 1;
  32281. Material._PointFillMode = 2;
  32282. // Draw modes
  32283. Material._PointListDrawMode = 3;
  32284. Material._LineListDrawMode = 4;
  32285. Material._LineLoopDrawMode = 5;
  32286. Material._LineStripDrawMode = 6;
  32287. Material._TriangleStripDrawMode = 7;
  32288. Material._TriangleFanDrawMode = 8;
  32289. /**
  32290. * Stores the clock-wise side orientation.
  32291. */
  32292. Material._ClockWiseSideOrientation = 0;
  32293. /**
  32294. * Stores the counter clock-wise side orientation.
  32295. */
  32296. Material._CounterClockWiseSideOrientation = 1;
  32297. /**
  32298. * The dirty texture flag value.
  32299. */
  32300. Material._TextureDirtyFlag = 1;
  32301. /**
  32302. * The dirty light flag value.
  32303. */
  32304. Material._LightDirtyFlag = 2;
  32305. /**
  32306. * The dirty fresnel flag value.
  32307. */
  32308. Material._FresnelDirtyFlag = 4;
  32309. /**
  32310. * The dirty attribute flag value.
  32311. */
  32312. Material._AttributesDirtyFlag = 8;
  32313. /**
  32314. * The dirty misc flag value.
  32315. */
  32316. Material._MiscDirtyFlag = 16;
  32317. __decorate([
  32318. BABYLON.serialize()
  32319. ], Material.prototype, "id", void 0);
  32320. __decorate([
  32321. BABYLON.serialize()
  32322. ], Material.prototype, "name", void 0);
  32323. __decorate([
  32324. BABYLON.serialize()
  32325. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32326. __decorate([
  32327. BABYLON.serialize()
  32328. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32329. __decorate([
  32330. BABYLON.serialize()
  32331. ], Material.prototype, "state", void 0);
  32332. __decorate([
  32333. BABYLON.serialize("alpha")
  32334. ], Material.prototype, "_alpha", void 0);
  32335. __decorate([
  32336. BABYLON.serialize("backFaceCulling")
  32337. ], Material.prototype, "_backFaceCulling", void 0);
  32338. __decorate([
  32339. BABYLON.serialize()
  32340. ], Material.prototype, "sideOrientation", void 0);
  32341. __decorate([
  32342. BABYLON.serialize("alphaMode")
  32343. ], Material.prototype, "_alphaMode", void 0);
  32344. __decorate([
  32345. BABYLON.serialize()
  32346. ], Material.prototype, "_needDepthPrePass", void 0);
  32347. __decorate([
  32348. BABYLON.serialize()
  32349. ], Material.prototype, "disableDepthWrite", void 0);
  32350. __decorate([
  32351. BABYLON.serialize()
  32352. ], Material.prototype, "forceDepthWrite", void 0);
  32353. __decorate([
  32354. BABYLON.serialize()
  32355. ], Material.prototype, "separateCullingPass", void 0);
  32356. __decorate([
  32357. BABYLON.serialize("fogEnabled")
  32358. ], Material.prototype, "_fogEnabled", void 0);
  32359. __decorate([
  32360. BABYLON.serialize()
  32361. ], Material.prototype, "pointSize", void 0);
  32362. __decorate([
  32363. BABYLON.serialize()
  32364. ], Material.prototype, "zOffset", void 0);
  32365. __decorate([
  32366. BABYLON.serialize()
  32367. ], Material.prototype, "wireframe", null);
  32368. __decorate([
  32369. BABYLON.serialize()
  32370. ], Material.prototype, "pointsCloud", null);
  32371. __decorate([
  32372. BABYLON.serialize()
  32373. ], Material.prototype, "fillMode", null);
  32374. return Material;
  32375. }());
  32376. BABYLON.Material = Material;
  32377. })(BABYLON || (BABYLON = {}));
  32378. //# sourceMappingURL=babylon.material.js.map
  32379. "use strict";
  32380. var BABYLON;
  32381. (function (BABYLON) {
  32382. var UniformBuffer = /** @class */ (function () {
  32383. /**
  32384. * Uniform buffer objects.
  32385. *
  32386. * Handles blocks of uniform on the GPU.
  32387. *
  32388. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32389. *
  32390. * For more information, please refer to :
  32391. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32392. */
  32393. function UniformBuffer(engine, data, dynamic) {
  32394. this._engine = engine;
  32395. this._noUBO = !engine.supportsUniformBuffers;
  32396. this._dynamic = dynamic;
  32397. this._data = data || [];
  32398. this._uniformLocations = {};
  32399. this._uniformSizes = {};
  32400. this._uniformLocationPointer = 0;
  32401. this._needSync = false;
  32402. if (this._noUBO) {
  32403. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32404. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32405. this.updateFloat = this._updateFloatForEffect;
  32406. this.updateFloat2 = this._updateFloat2ForEffect;
  32407. this.updateFloat3 = this._updateFloat3ForEffect;
  32408. this.updateFloat4 = this._updateFloat4ForEffect;
  32409. this.updateMatrix = this._updateMatrixForEffect;
  32410. this.updateVector3 = this._updateVector3ForEffect;
  32411. this.updateVector4 = this._updateVector4ForEffect;
  32412. this.updateColor3 = this._updateColor3ForEffect;
  32413. this.updateColor4 = this._updateColor4ForEffect;
  32414. }
  32415. else {
  32416. this._engine._uniformBuffers.push(this);
  32417. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32418. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32419. this.updateFloat = this._updateFloatForUniform;
  32420. this.updateFloat2 = this._updateFloat2ForUniform;
  32421. this.updateFloat3 = this._updateFloat3ForUniform;
  32422. this.updateFloat4 = this._updateFloat4ForUniform;
  32423. this.updateMatrix = this._updateMatrixForUniform;
  32424. this.updateVector3 = this._updateVector3ForUniform;
  32425. this.updateVector4 = this._updateVector4ForUniform;
  32426. this.updateColor3 = this._updateColor3ForUniform;
  32427. this.updateColor4 = this._updateColor4ForUniform;
  32428. }
  32429. }
  32430. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32431. // Properties
  32432. /**
  32433. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32434. * or just falling back on setUniformXXX calls.
  32435. */
  32436. get: function () {
  32437. return !this._noUBO;
  32438. },
  32439. enumerable: true,
  32440. configurable: true
  32441. });
  32442. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32443. /**
  32444. * Indicates if the WebGL underlying uniform buffer is in sync
  32445. * with the javascript cache data.
  32446. */
  32447. get: function () {
  32448. return !this._needSync;
  32449. },
  32450. enumerable: true,
  32451. configurable: true
  32452. });
  32453. /**
  32454. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32455. * Also, a dynamic UniformBuffer will disable cache verification and always
  32456. * update the underlying WebGL uniform buffer to the GPU.
  32457. */
  32458. UniformBuffer.prototype.isDynamic = function () {
  32459. return this._dynamic !== undefined;
  32460. };
  32461. /**
  32462. * The data cache on JS side.
  32463. */
  32464. UniformBuffer.prototype.getData = function () {
  32465. return this._bufferData;
  32466. };
  32467. /**
  32468. * The underlying WebGL Uniform buffer.
  32469. */
  32470. UniformBuffer.prototype.getBuffer = function () {
  32471. return this._buffer;
  32472. };
  32473. /**
  32474. * std140 layout specifies how to align data within an UBO structure.
  32475. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32476. * for specs.
  32477. */
  32478. UniformBuffer.prototype._fillAlignment = function (size) {
  32479. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32480. // and 4x4 matrices
  32481. // TODO : change if other types are used
  32482. var alignment;
  32483. if (size <= 2) {
  32484. alignment = size;
  32485. }
  32486. else {
  32487. alignment = 4;
  32488. }
  32489. if ((this._uniformLocationPointer % alignment) !== 0) {
  32490. var oldPointer = this._uniformLocationPointer;
  32491. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32492. var diff = this._uniformLocationPointer - oldPointer;
  32493. for (var i = 0; i < diff; i++) {
  32494. this._data.push(0);
  32495. }
  32496. }
  32497. };
  32498. /**
  32499. * Adds an uniform in the buffer.
  32500. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32501. * for the layout to be correct !
  32502. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32503. * @param {number|number[]} size Data size, or data directly.
  32504. */
  32505. UniformBuffer.prototype.addUniform = function (name, size) {
  32506. if (this._noUBO) {
  32507. return;
  32508. }
  32509. if (this._uniformLocations[name] !== undefined) {
  32510. // Already existing uniform
  32511. return;
  32512. }
  32513. // This function must be called in the order of the shader layout !
  32514. // size can be the size of the uniform, or data directly
  32515. var data;
  32516. if (size instanceof Array) {
  32517. data = size;
  32518. size = data.length;
  32519. }
  32520. else {
  32521. size = size;
  32522. data = [];
  32523. // Fill with zeros
  32524. for (var i = 0; i < size; i++) {
  32525. data.push(0);
  32526. }
  32527. }
  32528. this._fillAlignment(size);
  32529. this._uniformSizes[name] = size;
  32530. this._uniformLocations[name] = this._uniformLocationPointer;
  32531. this._uniformLocationPointer += size;
  32532. for (var i = 0; i < size; i++) {
  32533. this._data.push(data[i]);
  32534. }
  32535. this._needSync = true;
  32536. };
  32537. /**
  32538. * Wrapper for addUniform.
  32539. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32540. * @param {Matrix} mat A 4x4 matrix.
  32541. */
  32542. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32543. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32544. };
  32545. /**
  32546. * Wrapper for addUniform.
  32547. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32548. * @param {number} x
  32549. * @param {number} y
  32550. */
  32551. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32552. var temp = [x, y];
  32553. this.addUniform(name, temp);
  32554. };
  32555. /**
  32556. * Wrapper for addUniform.
  32557. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32558. * @param {number} x
  32559. * @param {number} y
  32560. * @param {number} z
  32561. */
  32562. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32563. var temp = [x, y, z];
  32564. this.addUniform(name, temp);
  32565. };
  32566. /**
  32567. * Wrapper for addUniform.
  32568. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32569. * @param {Color3} color
  32570. */
  32571. UniformBuffer.prototype.addColor3 = function (name, color) {
  32572. var temp = new Array();
  32573. color.toArray(temp);
  32574. this.addUniform(name, temp);
  32575. };
  32576. /**
  32577. * Wrapper for addUniform.
  32578. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32579. * @param {Color3} color
  32580. * @param {number} alpha
  32581. */
  32582. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32583. var temp = new Array();
  32584. color.toArray(temp);
  32585. temp.push(alpha);
  32586. this.addUniform(name, temp);
  32587. };
  32588. /**
  32589. * Wrapper for addUniform.
  32590. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32591. * @param {Vector3} vector
  32592. */
  32593. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32594. var temp = new Array();
  32595. vector.toArray(temp);
  32596. this.addUniform(name, temp);
  32597. };
  32598. /**
  32599. * Wrapper for addUniform.
  32600. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32601. */
  32602. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32603. this.addUniform(name, 12);
  32604. };
  32605. /**
  32606. * Wrapper for addUniform.
  32607. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32608. */
  32609. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32610. this.addUniform(name, 8);
  32611. };
  32612. /**
  32613. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32614. */
  32615. UniformBuffer.prototype.create = function () {
  32616. if (this._noUBO) {
  32617. return;
  32618. }
  32619. if (this._buffer) {
  32620. return; // nothing to do
  32621. }
  32622. // See spec, alignment must be filled as a vec4
  32623. this._fillAlignment(4);
  32624. this._bufferData = new Float32Array(this._data);
  32625. this._rebuild();
  32626. this._needSync = true;
  32627. };
  32628. UniformBuffer.prototype._rebuild = function () {
  32629. if (this._noUBO) {
  32630. return;
  32631. }
  32632. if (this._dynamic) {
  32633. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32634. }
  32635. else {
  32636. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32637. }
  32638. };
  32639. /**
  32640. * Updates the WebGL Uniform Buffer on the GPU.
  32641. * If the `dynamic` flag is set to true, no cache comparison is done.
  32642. * Otherwise, the buffer will be updated only if the cache differs.
  32643. */
  32644. UniformBuffer.prototype.update = function () {
  32645. if (!this._buffer) {
  32646. this.create();
  32647. return;
  32648. }
  32649. if (!this._dynamic && !this._needSync) {
  32650. return;
  32651. }
  32652. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32653. this._needSync = false;
  32654. };
  32655. /**
  32656. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32657. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32658. * @param {number[]|Float32Array} data Flattened data
  32659. * @param {number} size Size of the data.
  32660. */
  32661. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32662. var location = this._uniformLocations[uniformName];
  32663. if (location === undefined) {
  32664. if (this._buffer) {
  32665. // Cannot add an uniform if the buffer is already created
  32666. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32667. return;
  32668. }
  32669. this.addUniform(uniformName, size);
  32670. location = this._uniformLocations[uniformName];
  32671. }
  32672. if (!this._buffer) {
  32673. this.create();
  32674. }
  32675. if (!this._dynamic) {
  32676. // Cache for static uniform buffers
  32677. var changed = false;
  32678. for (var i = 0; i < size; i++) {
  32679. if (this._bufferData[location + i] !== data[i]) {
  32680. changed = true;
  32681. this._bufferData[location + i] = data[i];
  32682. }
  32683. }
  32684. this._needSync = this._needSync || changed;
  32685. }
  32686. else {
  32687. // No cache for dynamic
  32688. for (var i = 0; i < size; i++) {
  32689. this._bufferData[location + i] = data[i];
  32690. }
  32691. }
  32692. };
  32693. // Update methods
  32694. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32695. // To match std140, matrix must be realigned
  32696. for (var i = 0; i < 3; i++) {
  32697. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32698. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32699. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32700. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32701. }
  32702. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32703. };
  32704. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32705. this._currentEffect.setMatrix3x3(name, matrix);
  32706. };
  32707. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32708. this._currentEffect.setMatrix2x2(name, matrix);
  32709. };
  32710. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32711. // To match std140, matrix must be realigned
  32712. for (var i = 0; i < 2; i++) {
  32713. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32714. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32715. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32716. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32717. }
  32718. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32719. };
  32720. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32721. this._currentEffect.setFloat(name, x);
  32722. };
  32723. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32724. UniformBuffer._tempBuffer[0] = x;
  32725. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32726. };
  32727. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32728. if (suffix === void 0) { suffix = ""; }
  32729. this._currentEffect.setFloat2(name + suffix, x, y);
  32730. };
  32731. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32732. if (suffix === void 0) { suffix = ""; }
  32733. UniformBuffer._tempBuffer[0] = x;
  32734. UniformBuffer._tempBuffer[1] = y;
  32735. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32736. };
  32737. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32738. if (suffix === void 0) { suffix = ""; }
  32739. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32740. };
  32741. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32742. if (suffix === void 0) { suffix = ""; }
  32743. UniformBuffer._tempBuffer[0] = x;
  32744. UniformBuffer._tempBuffer[1] = y;
  32745. UniformBuffer._tempBuffer[2] = z;
  32746. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32747. };
  32748. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32749. if (suffix === void 0) { suffix = ""; }
  32750. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32751. };
  32752. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32753. if (suffix === void 0) { suffix = ""; }
  32754. UniformBuffer._tempBuffer[0] = x;
  32755. UniformBuffer._tempBuffer[1] = y;
  32756. UniformBuffer._tempBuffer[2] = z;
  32757. UniformBuffer._tempBuffer[3] = w;
  32758. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32759. };
  32760. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32761. this._currentEffect.setMatrix(name, mat);
  32762. };
  32763. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32764. this.updateUniform(name, mat.toArray(), 16);
  32765. };
  32766. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32767. this._currentEffect.setVector3(name, vector);
  32768. };
  32769. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32770. vector.toArray(UniformBuffer._tempBuffer);
  32771. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32772. };
  32773. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32774. this._currentEffect.setVector4(name, vector);
  32775. };
  32776. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32777. vector.toArray(UniformBuffer._tempBuffer);
  32778. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32779. };
  32780. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32781. if (suffix === void 0) { suffix = ""; }
  32782. this._currentEffect.setColor3(name + suffix, color);
  32783. };
  32784. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32785. if (suffix === void 0) { suffix = ""; }
  32786. color.toArray(UniformBuffer._tempBuffer);
  32787. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32788. };
  32789. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32790. if (suffix === void 0) { suffix = ""; }
  32791. this._currentEffect.setColor4(name + suffix, color, alpha);
  32792. };
  32793. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32794. if (suffix === void 0) { suffix = ""; }
  32795. color.toArray(UniformBuffer._tempBuffer);
  32796. UniformBuffer._tempBuffer[3] = alpha;
  32797. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32798. };
  32799. /**
  32800. * Sets a sampler uniform on the effect.
  32801. * @param {string} name Name of the sampler.
  32802. * @param {Texture} texture
  32803. */
  32804. UniformBuffer.prototype.setTexture = function (name, texture) {
  32805. this._currentEffect.setTexture(name, texture);
  32806. };
  32807. /**
  32808. * Directly updates the value of the uniform in the cache AND on the GPU.
  32809. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32810. * @param {number[]|Float32Array} data Flattened data
  32811. */
  32812. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32813. this.updateUniform(uniformName, data, data.length);
  32814. this.update();
  32815. };
  32816. /**
  32817. * Binds this uniform buffer to an effect.
  32818. * @param {Effect} effect
  32819. * @param {string} name Name of the uniform block in the shader.
  32820. */
  32821. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32822. this._currentEffect = effect;
  32823. if (this._noUBO || !this._buffer) {
  32824. return;
  32825. }
  32826. effect.bindUniformBuffer(this._buffer, name);
  32827. };
  32828. /**
  32829. * Disposes the uniform buffer.
  32830. */
  32831. UniformBuffer.prototype.dispose = function () {
  32832. if (this._noUBO) {
  32833. return;
  32834. }
  32835. var index = this._engine._uniformBuffers.indexOf(this);
  32836. if (index !== -1) {
  32837. this._engine._uniformBuffers.splice(index, 1);
  32838. }
  32839. if (!this._buffer) {
  32840. return;
  32841. }
  32842. if (this._engine._releaseBuffer(this._buffer)) {
  32843. this._buffer = null;
  32844. }
  32845. };
  32846. // Pool for avoiding memory leaks
  32847. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32848. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32849. return UniformBuffer;
  32850. }());
  32851. BABYLON.UniformBuffer = UniformBuffer;
  32852. })(BABYLON || (BABYLON = {}));
  32853. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32854. "use strict";
  32855. var BABYLON;
  32856. (function (BABYLON) {
  32857. var VertexData = /** @class */ (function () {
  32858. function VertexData() {
  32859. }
  32860. VertexData.prototype.set = function (data, kind) {
  32861. switch (kind) {
  32862. case BABYLON.VertexBuffer.PositionKind:
  32863. this.positions = data;
  32864. break;
  32865. case BABYLON.VertexBuffer.NormalKind:
  32866. this.normals = data;
  32867. break;
  32868. case BABYLON.VertexBuffer.TangentKind:
  32869. this.tangents = data;
  32870. break;
  32871. case BABYLON.VertexBuffer.UVKind:
  32872. this.uvs = data;
  32873. break;
  32874. case BABYLON.VertexBuffer.UV2Kind:
  32875. this.uvs2 = data;
  32876. break;
  32877. case BABYLON.VertexBuffer.UV3Kind:
  32878. this.uvs3 = data;
  32879. break;
  32880. case BABYLON.VertexBuffer.UV4Kind:
  32881. this.uvs4 = data;
  32882. break;
  32883. case BABYLON.VertexBuffer.UV5Kind:
  32884. this.uvs5 = data;
  32885. break;
  32886. case BABYLON.VertexBuffer.UV6Kind:
  32887. this.uvs6 = data;
  32888. break;
  32889. case BABYLON.VertexBuffer.ColorKind:
  32890. this.colors = data;
  32891. break;
  32892. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32893. this.matricesIndices = data;
  32894. break;
  32895. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32896. this.matricesWeights = data;
  32897. break;
  32898. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32899. this.matricesIndicesExtra = data;
  32900. break;
  32901. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32902. this.matricesWeightsExtra = data;
  32903. break;
  32904. }
  32905. };
  32906. /**
  32907. * Associates the vertexData to the passed Mesh.
  32908. * Sets it as updatable or not (default `false`).
  32909. * Returns the VertexData.
  32910. */
  32911. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32912. this._applyTo(mesh, updatable);
  32913. return this;
  32914. };
  32915. /**
  32916. * Associates the vertexData to the passed Geometry.
  32917. * Sets it as updatable or not (default `false`).
  32918. * Returns the VertexData.
  32919. */
  32920. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32921. this._applyTo(geometry, updatable);
  32922. return this;
  32923. };
  32924. /**
  32925. * Updates the associated mesh.
  32926. * Returns the VertexData.
  32927. */
  32928. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32929. this._update(mesh);
  32930. return this;
  32931. };
  32932. /**
  32933. * Updates the associated geometry.
  32934. * Returns the VertexData.
  32935. */
  32936. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32937. this._update(geometry);
  32938. return this;
  32939. };
  32940. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32941. if (updatable === void 0) { updatable = false; }
  32942. if (this.positions) {
  32943. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32944. }
  32945. if (this.normals) {
  32946. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32947. }
  32948. if (this.tangents) {
  32949. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32950. }
  32951. if (this.uvs) {
  32952. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32953. }
  32954. if (this.uvs2) {
  32955. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32956. }
  32957. if (this.uvs3) {
  32958. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32959. }
  32960. if (this.uvs4) {
  32961. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32962. }
  32963. if (this.uvs5) {
  32964. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32965. }
  32966. if (this.uvs6) {
  32967. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32968. }
  32969. if (this.colors) {
  32970. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32971. }
  32972. if (this.matricesIndices) {
  32973. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32974. }
  32975. if (this.matricesWeights) {
  32976. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32977. }
  32978. if (this.matricesIndicesExtra) {
  32979. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32980. }
  32981. if (this.matricesWeightsExtra) {
  32982. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32983. }
  32984. if (this.indices) {
  32985. meshOrGeometry.setIndices(this.indices, null, updatable);
  32986. }
  32987. return this;
  32988. };
  32989. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32990. if (this.positions) {
  32991. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32992. }
  32993. if (this.normals) {
  32994. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32995. }
  32996. if (this.tangents) {
  32997. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32998. }
  32999. if (this.uvs) {
  33000. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33001. }
  33002. if (this.uvs2) {
  33003. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33004. }
  33005. if (this.uvs3) {
  33006. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33007. }
  33008. if (this.uvs4) {
  33009. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33010. }
  33011. if (this.uvs5) {
  33012. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33013. }
  33014. if (this.uvs6) {
  33015. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33016. }
  33017. if (this.colors) {
  33018. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33019. }
  33020. if (this.matricesIndices) {
  33021. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33022. }
  33023. if (this.matricesWeights) {
  33024. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33025. }
  33026. if (this.matricesIndicesExtra) {
  33027. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33028. }
  33029. if (this.matricesWeightsExtra) {
  33030. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33031. }
  33032. if (this.indices) {
  33033. meshOrGeometry.setIndices(this.indices, null);
  33034. }
  33035. return this;
  33036. };
  33037. /**
  33038. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33039. * Returns the VertexData.
  33040. */
  33041. VertexData.prototype.transform = function (matrix) {
  33042. var transformed = BABYLON.Vector3.Zero();
  33043. var index;
  33044. if (this.positions) {
  33045. var position = BABYLON.Vector3.Zero();
  33046. for (index = 0; index < this.positions.length; index += 3) {
  33047. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33048. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33049. this.positions[index] = transformed.x;
  33050. this.positions[index + 1] = transformed.y;
  33051. this.positions[index + 2] = transformed.z;
  33052. }
  33053. }
  33054. if (this.normals) {
  33055. var normal = BABYLON.Vector3.Zero();
  33056. for (index = 0; index < this.normals.length; index += 3) {
  33057. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33058. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33059. this.normals[index] = transformed.x;
  33060. this.normals[index + 1] = transformed.y;
  33061. this.normals[index + 2] = transformed.z;
  33062. }
  33063. }
  33064. if (this.tangents) {
  33065. var tangent = BABYLON.Vector4.Zero();
  33066. var tangentTransformed = BABYLON.Vector4.Zero();
  33067. for (index = 0; index < this.tangents.length; index += 4) {
  33068. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33069. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33070. this.tangents[index] = tangentTransformed.x;
  33071. this.tangents[index + 1] = tangentTransformed.y;
  33072. this.tangents[index + 2] = tangentTransformed.z;
  33073. this.tangents[index + 3] = tangentTransformed.w;
  33074. }
  33075. }
  33076. return this;
  33077. };
  33078. /**
  33079. * Merges the passed VertexData into the current one.
  33080. * Returns the modified VertexData.
  33081. */
  33082. VertexData.prototype.merge = function (other) {
  33083. this._validate();
  33084. other._validate();
  33085. if (!this.normals !== !other.normals ||
  33086. !this.tangents !== !other.tangents ||
  33087. !this.uvs !== !other.uvs ||
  33088. !this.uvs2 !== !other.uvs2 ||
  33089. !this.uvs3 !== !other.uvs3 ||
  33090. !this.uvs4 !== !other.uvs4 ||
  33091. !this.uvs5 !== !other.uvs5 ||
  33092. !this.uvs6 !== !other.uvs6 ||
  33093. !this.colors !== !other.colors ||
  33094. !this.matricesIndices !== !other.matricesIndices ||
  33095. !this.matricesWeights !== !other.matricesWeights ||
  33096. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33097. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33098. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33099. }
  33100. if (other.indices) {
  33101. if (!this.indices) {
  33102. this.indices = [];
  33103. }
  33104. var offset = this.positions ? this.positions.length / 3 : 0;
  33105. for (var index = 0; index < other.indices.length; index++) {
  33106. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33107. this.indices.push(other.indices[index] + offset);
  33108. }
  33109. }
  33110. this.positions = this._mergeElement(this.positions, other.positions);
  33111. this.normals = this._mergeElement(this.normals, other.normals);
  33112. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33113. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33114. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33115. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33116. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33117. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33118. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33119. this.colors = this._mergeElement(this.colors, other.colors);
  33120. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33121. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33122. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33123. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33124. return this;
  33125. };
  33126. VertexData.prototype._mergeElement = function (source, other) {
  33127. if (!source) {
  33128. return other;
  33129. }
  33130. if (!other) {
  33131. return source;
  33132. }
  33133. var len = other.length + source.length;
  33134. var isSrcTypedArray = source instanceof Float32Array;
  33135. var isOthTypedArray = other instanceof Float32Array;
  33136. // use non-loop method when the source is Float32Array
  33137. if (isSrcTypedArray) {
  33138. var ret32 = new Float32Array(len);
  33139. ret32.set(source);
  33140. ret32.set(other, source.length);
  33141. return ret32;
  33142. // source is number[], when other is also use concat
  33143. }
  33144. else if (!isOthTypedArray) {
  33145. return source.concat(other);
  33146. // source is a number[], but other is a Float32Array, loop required
  33147. }
  33148. else {
  33149. var ret = source.slice(0); // copy source to a separate array
  33150. for (var i = 0, len = other.length; i < len; i++) {
  33151. ret.push(other[i]);
  33152. }
  33153. return ret;
  33154. }
  33155. };
  33156. VertexData.prototype._validate = function () {
  33157. if (!this.positions) {
  33158. throw new Error("Positions are required");
  33159. }
  33160. var getElementCount = function (kind, values) {
  33161. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33162. if ((values.length % stride) !== 0) {
  33163. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33164. }
  33165. return values.length / stride;
  33166. };
  33167. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33168. var validateElementCount = function (kind, values) {
  33169. var elementCount = getElementCount(kind, values);
  33170. if (elementCount !== positionsElementCount) {
  33171. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33172. }
  33173. };
  33174. if (this.normals)
  33175. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33176. if (this.tangents)
  33177. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33178. if (this.uvs)
  33179. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33180. if (this.uvs2)
  33181. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33182. if (this.uvs3)
  33183. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33184. if (this.uvs4)
  33185. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33186. if (this.uvs5)
  33187. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33188. if (this.uvs6)
  33189. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33190. if (this.colors)
  33191. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33192. if (this.matricesIndices)
  33193. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33194. if (this.matricesWeights)
  33195. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33196. if (this.matricesIndicesExtra)
  33197. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33198. if (this.matricesWeightsExtra)
  33199. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33200. };
  33201. /**
  33202. * Serializes the VertexData.
  33203. * Returns a serialized object.
  33204. */
  33205. VertexData.prototype.serialize = function () {
  33206. var serializationObject = this.serialize();
  33207. if (this.positions) {
  33208. serializationObject.positions = this.positions;
  33209. }
  33210. if (this.normals) {
  33211. serializationObject.normals = this.normals;
  33212. }
  33213. if (this.tangents) {
  33214. serializationObject.tangents = this.tangents;
  33215. }
  33216. if (this.uvs) {
  33217. serializationObject.uvs = this.uvs;
  33218. }
  33219. if (this.uvs2) {
  33220. serializationObject.uvs2 = this.uvs2;
  33221. }
  33222. if (this.uvs3) {
  33223. serializationObject.uvs3 = this.uvs3;
  33224. }
  33225. if (this.uvs4) {
  33226. serializationObject.uvs4 = this.uvs4;
  33227. }
  33228. if (this.uvs5) {
  33229. serializationObject.uvs5 = this.uvs5;
  33230. }
  33231. if (this.uvs6) {
  33232. serializationObject.uvs6 = this.uvs6;
  33233. }
  33234. if (this.colors) {
  33235. serializationObject.colors = this.colors;
  33236. }
  33237. if (this.matricesIndices) {
  33238. serializationObject.matricesIndices = this.matricesIndices;
  33239. serializationObject.matricesIndices._isExpanded = true;
  33240. }
  33241. if (this.matricesWeights) {
  33242. serializationObject.matricesWeights = this.matricesWeights;
  33243. }
  33244. if (this.matricesIndicesExtra) {
  33245. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33246. serializationObject.matricesIndicesExtra._isExpanded = true;
  33247. }
  33248. if (this.matricesWeightsExtra) {
  33249. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33250. }
  33251. serializationObject.indices = this.indices;
  33252. return serializationObject;
  33253. };
  33254. // Statics
  33255. /**
  33256. * Returns the object VertexData associated to the passed mesh.
  33257. */
  33258. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33259. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33260. };
  33261. /**
  33262. * Returns the object VertexData associated to the passed geometry.
  33263. */
  33264. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33265. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33266. };
  33267. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33268. var result = new VertexData();
  33269. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33270. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33271. }
  33272. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33273. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33274. }
  33275. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33276. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33277. }
  33278. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33279. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33280. }
  33281. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33282. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33283. }
  33284. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33285. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33286. }
  33287. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33288. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33289. }
  33290. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33291. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33292. }
  33293. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33294. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33295. }
  33296. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33297. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33298. }
  33299. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33300. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33301. }
  33302. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33303. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33304. }
  33305. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33306. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33307. }
  33308. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33309. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33310. }
  33311. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33312. return result;
  33313. };
  33314. /**
  33315. * Creates the vertexData of the Ribbon.
  33316. */
  33317. VertexData.CreateRibbon = function (options) {
  33318. var pathArray = options.pathArray;
  33319. var closeArray = options.closeArray || false;
  33320. var closePath = options.closePath || false;
  33321. var invertUV = options.invertUV || false;
  33322. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33323. var offset = options.offset || defaultOffset;
  33324. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33325. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33326. var customUV = options.uvs;
  33327. var customColors = options.colors;
  33328. var positions = [];
  33329. var indices = [];
  33330. var normals = [];
  33331. var uvs = [];
  33332. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33333. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33334. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33335. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33336. var minlg; // minimal length among all paths from pathArray
  33337. var lg = []; // array of path lengths : nb of vertex per path
  33338. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33339. var p; // path iterator
  33340. var i; // point iterator
  33341. var j; // point iterator
  33342. // if single path in pathArray
  33343. if (pathArray.length < 2) {
  33344. var ar1 = [];
  33345. var ar2 = [];
  33346. for (i = 0; i < pathArray[0].length - offset; i++) {
  33347. ar1.push(pathArray[0][i]);
  33348. ar2.push(pathArray[0][i + offset]);
  33349. }
  33350. pathArray = [ar1, ar2];
  33351. }
  33352. // positions and horizontal distances (u)
  33353. var idc = 0;
  33354. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33355. var path;
  33356. var l;
  33357. minlg = pathArray[0].length;
  33358. var vectlg;
  33359. var dist;
  33360. for (p = 0; p < pathArray.length; p++) {
  33361. uTotalDistance[p] = 0;
  33362. us[p] = [0];
  33363. path = pathArray[p];
  33364. l = path.length;
  33365. minlg = (minlg < l) ? minlg : l;
  33366. j = 0;
  33367. while (j < l) {
  33368. positions.push(path[j].x, path[j].y, path[j].z);
  33369. if (j > 0) {
  33370. vectlg = path[j].subtract(path[j - 1]).length();
  33371. dist = vectlg + uTotalDistance[p];
  33372. us[p].push(dist);
  33373. uTotalDistance[p] = dist;
  33374. }
  33375. j++;
  33376. }
  33377. if (closePath) {
  33378. j--;
  33379. positions.push(path[0].x, path[0].y, path[0].z);
  33380. vectlg = path[j].subtract(path[0]).length();
  33381. dist = vectlg + uTotalDistance[p];
  33382. us[p].push(dist);
  33383. uTotalDistance[p] = dist;
  33384. }
  33385. lg[p] = l + closePathCorr;
  33386. idx[p] = idc;
  33387. idc += (l + closePathCorr);
  33388. }
  33389. // vertical distances (v)
  33390. var path1;
  33391. var path2;
  33392. var vertex1 = null;
  33393. var vertex2 = null;
  33394. for (i = 0; i < minlg + closePathCorr; i++) {
  33395. vTotalDistance[i] = 0;
  33396. vs[i] = [0];
  33397. for (p = 0; p < pathArray.length - 1; p++) {
  33398. path1 = pathArray[p];
  33399. path2 = pathArray[p + 1];
  33400. if (i === minlg) {
  33401. vertex1 = path1[0];
  33402. vertex2 = path2[0];
  33403. }
  33404. else {
  33405. vertex1 = path1[i];
  33406. vertex2 = path2[i];
  33407. }
  33408. vectlg = vertex2.subtract(vertex1).length();
  33409. dist = vectlg + vTotalDistance[i];
  33410. vs[i].push(dist);
  33411. vTotalDistance[i] = dist;
  33412. }
  33413. if (closeArray && vertex2 && vertex1) {
  33414. path1 = pathArray[p];
  33415. path2 = pathArray[0];
  33416. if (i === minlg) {
  33417. vertex2 = path2[0];
  33418. }
  33419. vectlg = vertex2.subtract(vertex1).length();
  33420. dist = vectlg + vTotalDistance[i];
  33421. vTotalDistance[i] = dist;
  33422. }
  33423. }
  33424. // uvs
  33425. var u;
  33426. var v;
  33427. if (customUV) {
  33428. for (p = 0; p < customUV.length; p++) {
  33429. uvs.push(customUV[p].x, customUV[p].y);
  33430. }
  33431. }
  33432. else {
  33433. for (p = 0; p < pathArray.length; p++) {
  33434. for (i = 0; i < minlg + closePathCorr; i++) {
  33435. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33436. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33437. if (invertUV) {
  33438. uvs.push(v, u);
  33439. }
  33440. else {
  33441. uvs.push(u, v);
  33442. }
  33443. }
  33444. }
  33445. }
  33446. // indices
  33447. p = 0; // path index
  33448. var pi = 0; // positions array index
  33449. var l1 = lg[p] - 1; // path1 length
  33450. var l2 = lg[p + 1] - 1; // path2 length
  33451. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33452. var shft = idx[1] - idx[0]; // shift
  33453. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33454. while (pi <= min && p < path1nb) {
  33455. // 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
  33456. indices.push(pi, pi + shft, pi + 1);
  33457. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33458. pi += 1;
  33459. if (pi === min) {
  33460. p++;
  33461. if (p === lg.length - 1) {
  33462. shft = idx[0] - idx[p];
  33463. l1 = lg[p] - 1;
  33464. l2 = lg[0] - 1;
  33465. }
  33466. else {
  33467. shft = idx[p + 1] - idx[p];
  33468. l1 = lg[p] - 1;
  33469. l2 = lg[p + 1] - 1;
  33470. }
  33471. pi = idx[p];
  33472. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33473. }
  33474. }
  33475. // normals
  33476. VertexData.ComputeNormals(positions, indices, normals);
  33477. if (closePath) {
  33478. var indexFirst = 0;
  33479. var indexLast = 0;
  33480. for (p = 0; p < pathArray.length; p++) {
  33481. indexFirst = idx[p] * 3;
  33482. if (p + 1 < pathArray.length) {
  33483. indexLast = (idx[p + 1] - 1) * 3;
  33484. }
  33485. else {
  33486. indexLast = normals.length - 3;
  33487. }
  33488. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33489. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33490. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33491. normals[indexLast] = normals[indexFirst];
  33492. normals[indexLast + 1] = normals[indexFirst + 1];
  33493. normals[indexLast + 2] = normals[indexFirst + 2];
  33494. }
  33495. }
  33496. // sides
  33497. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33498. // Colors
  33499. var colors = null;
  33500. if (customColors) {
  33501. colors = new Float32Array(customColors.length * 4);
  33502. for (var c = 0; c < customColors.length; c++) {
  33503. colors[c * 4] = customColors[c].r;
  33504. colors[c * 4 + 1] = customColors[c].g;
  33505. colors[c * 4 + 2] = customColors[c].b;
  33506. colors[c * 4 + 3] = customColors[c].a;
  33507. }
  33508. }
  33509. // Result
  33510. var vertexData = new VertexData();
  33511. var positions32 = new Float32Array(positions);
  33512. var normals32 = new Float32Array(normals);
  33513. var uvs32 = new Float32Array(uvs);
  33514. vertexData.indices = indices;
  33515. vertexData.positions = positions32;
  33516. vertexData.normals = normals32;
  33517. vertexData.uvs = uvs32;
  33518. if (colors) {
  33519. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33520. }
  33521. if (closePath) {
  33522. vertexData._idx = idx;
  33523. }
  33524. return vertexData;
  33525. };
  33526. /**
  33527. * Creates the VertexData of the Box.
  33528. */
  33529. VertexData.CreateBox = function (options) {
  33530. var normalsSource = [
  33531. new BABYLON.Vector3(0, 0, 1),
  33532. new BABYLON.Vector3(0, 0, -1),
  33533. new BABYLON.Vector3(1, 0, 0),
  33534. new BABYLON.Vector3(-1, 0, 0),
  33535. new BABYLON.Vector3(0, 1, 0),
  33536. new BABYLON.Vector3(0, -1, 0)
  33537. ];
  33538. var indices = [];
  33539. var positions = [];
  33540. var normals = [];
  33541. var uvs = [];
  33542. var width = options.width || options.size || 1;
  33543. var height = options.height || options.size || 1;
  33544. var depth = options.depth || options.size || 1;
  33545. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33546. var faceUV = options.faceUV || new Array(6);
  33547. var faceColors = options.faceColors;
  33548. var colors = [];
  33549. // default face colors and UV if undefined
  33550. for (var f = 0; f < 6; f++) {
  33551. if (faceUV[f] === undefined) {
  33552. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33553. }
  33554. if (faceColors && faceColors[f] === undefined) {
  33555. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33556. }
  33557. }
  33558. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33559. // Create each face in turn.
  33560. for (var index = 0; index < normalsSource.length; index++) {
  33561. var normal = normalsSource[index];
  33562. // Get two vectors perpendicular to the face normal and to each other.
  33563. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33564. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33565. // Six indices (two triangles) per face.
  33566. var verticesLength = positions.length / 3;
  33567. indices.push(verticesLength);
  33568. indices.push(verticesLength + 1);
  33569. indices.push(verticesLength + 2);
  33570. indices.push(verticesLength);
  33571. indices.push(verticesLength + 2);
  33572. indices.push(verticesLength + 3);
  33573. // Four vertices per face.
  33574. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33575. positions.push(vertex.x, vertex.y, vertex.z);
  33576. normals.push(normal.x, normal.y, normal.z);
  33577. uvs.push(faceUV[index].z, faceUV[index].w);
  33578. if (faceColors) {
  33579. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33580. }
  33581. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33582. positions.push(vertex.x, vertex.y, vertex.z);
  33583. normals.push(normal.x, normal.y, normal.z);
  33584. uvs.push(faceUV[index].x, faceUV[index].w);
  33585. if (faceColors) {
  33586. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33587. }
  33588. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33589. positions.push(vertex.x, vertex.y, vertex.z);
  33590. normals.push(normal.x, normal.y, normal.z);
  33591. uvs.push(faceUV[index].x, faceUV[index].y);
  33592. if (faceColors) {
  33593. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33594. }
  33595. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33596. positions.push(vertex.x, vertex.y, vertex.z);
  33597. normals.push(normal.x, normal.y, normal.z);
  33598. uvs.push(faceUV[index].z, faceUV[index].y);
  33599. if (faceColors) {
  33600. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33601. }
  33602. }
  33603. // sides
  33604. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33605. // Result
  33606. var vertexData = new VertexData();
  33607. vertexData.indices = indices;
  33608. vertexData.positions = positions;
  33609. vertexData.normals = normals;
  33610. vertexData.uvs = uvs;
  33611. if (faceColors) {
  33612. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33613. vertexData.colors = totalColors;
  33614. }
  33615. return vertexData;
  33616. };
  33617. /**
  33618. * Creates the VertexData of the Sphere.
  33619. */
  33620. VertexData.CreateSphere = function (options) {
  33621. var segments = options.segments || 32;
  33622. var diameterX = options.diameterX || options.diameter || 1;
  33623. var diameterY = options.diameterY || options.diameter || 1;
  33624. var diameterZ = options.diameterZ || options.diameter || 1;
  33625. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33626. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33627. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33628. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33629. var totalZRotationSteps = 2 + segments;
  33630. var totalYRotationSteps = 2 * totalZRotationSteps;
  33631. var indices = [];
  33632. var positions = [];
  33633. var normals = [];
  33634. var uvs = [];
  33635. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33636. var normalizedZ = zRotationStep / totalZRotationSteps;
  33637. var angleZ = normalizedZ * Math.PI * slice;
  33638. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33639. var normalizedY = yRotationStep / totalYRotationSteps;
  33640. var angleY = normalizedY * Math.PI * 2 * arc;
  33641. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33642. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33643. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33644. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33645. var vertex = complete.multiply(radius);
  33646. var normal = complete.divide(radius).normalize();
  33647. positions.push(vertex.x, vertex.y, vertex.z);
  33648. normals.push(normal.x, normal.y, normal.z);
  33649. uvs.push(normalizedY, normalizedZ);
  33650. }
  33651. if (zRotationStep > 0) {
  33652. var verticesCount = positions.length / 3;
  33653. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33654. indices.push((firstIndex));
  33655. indices.push((firstIndex + 1));
  33656. indices.push(firstIndex + totalYRotationSteps + 1);
  33657. indices.push((firstIndex + totalYRotationSteps + 1));
  33658. indices.push((firstIndex + 1));
  33659. indices.push((firstIndex + totalYRotationSteps + 2));
  33660. }
  33661. }
  33662. }
  33663. // Sides
  33664. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33665. // Result
  33666. var vertexData = new VertexData();
  33667. vertexData.indices = indices;
  33668. vertexData.positions = positions;
  33669. vertexData.normals = normals;
  33670. vertexData.uvs = uvs;
  33671. return vertexData;
  33672. };
  33673. /**
  33674. * Creates the VertexData of the Cylinder or Cone.
  33675. */
  33676. VertexData.CreateCylinder = function (options) {
  33677. var height = options.height || 2;
  33678. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33679. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33680. var tessellation = options.tessellation || 24;
  33681. var subdivisions = options.subdivisions || 1;
  33682. var hasRings = options.hasRings ? true : false;
  33683. var enclose = options.enclose ? true : false;
  33684. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33685. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33686. var faceUV = options.faceUV || new Array(3);
  33687. var faceColors = options.faceColors;
  33688. // default face colors and UV if undefined
  33689. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33690. var ringNb = (hasRings) ? subdivisions : 1;
  33691. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33692. var f;
  33693. for (f = 0; f < surfaceNb; f++) {
  33694. if (faceColors && faceColors[f] === undefined) {
  33695. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33696. }
  33697. }
  33698. for (f = 0; f < surfaceNb; f++) {
  33699. if (faceUV && faceUV[f] === undefined) {
  33700. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33701. }
  33702. }
  33703. var indices = new Array();
  33704. var positions = new Array();
  33705. var normals = new Array();
  33706. var uvs = new Array();
  33707. var colors = new Array();
  33708. var angle_step = Math.PI * 2 * arc / tessellation;
  33709. var angle;
  33710. var h;
  33711. var radius;
  33712. var tan = (diameterBottom - diameterTop) / 2 / height;
  33713. var ringVertex = BABYLON.Vector3.Zero();
  33714. var ringNormal = BABYLON.Vector3.Zero();
  33715. var ringFirstVertex = BABYLON.Vector3.Zero();
  33716. var ringFirstNormal = BABYLON.Vector3.Zero();
  33717. var quadNormal = BABYLON.Vector3.Zero();
  33718. var Y = BABYLON.Axis.Y;
  33719. // positions, normals, uvs
  33720. var i;
  33721. var j;
  33722. var r;
  33723. var ringIdx = 1;
  33724. var s = 1; // surface index
  33725. var cs = 0;
  33726. var v = 0;
  33727. for (i = 0; i <= subdivisions; i++) {
  33728. h = i / subdivisions;
  33729. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33730. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33731. for (r = 0; r < ringIdx; r++) {
  33732. if (hasRings) {
  33733. s += r;
  33734. }
  33735. if (enclose) {
  33736. s += 2 * r;
  33737. }
  33738. for (j = 0; j <= tessellation; j++) {
  33739. angle = j * angle_step;
  33740. // position
  33741. ringVertex.x = Math.cos(-angle) * radius;
  33742. ringVertex.y = -height / 2 + h * height;
  33743. ringVertex.z = Math.sin(-angle) * radius;
  33744. // normal
  33745. if (diameterTop === 0 && i === subdivisions) {
  33746. // if no top cap, reuse former normals
  33747. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33748. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33749. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33750. }
  33751. else {
  33752. ringNormal.x = ringVertex.x;
  33753. ringNormal.z = ringVertex.z;
  33754. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33755. ringNormal.normalize();
  33756. }
  33757. // keep first ring vertex values for enclose
  33758. if (j === 0) {
  33759. ringFirstVertex.copyFrom(ringVertex);
  33760. ringFirstNormal.copyFrom(ringNormal);
  33761. }
  33762. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33763. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33764. if (hasRings) {
  33765. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33766. }
  33767. else {
  33768. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33769. }
  33770. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33771. if (faceColors) {
  33772. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33773. }
  33774. }
  33775. // if enclose, add four vertices and their dedicated normals
  33776. if (arc !== 1 && enclose) {
  33777. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33778. positions.push(0, ringVertex.y, 0);
  33779. positions.push(0, ringVertex.y, 0);
  33780. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33781. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33782. quadNormal.normalize();
  33783. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33784. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33785. quadNormal.normalize();
  33786. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33787. if (hasRings) {
  33788. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33789. }
  33790. else {
  33791. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33792. }
  33793. uvs.push(faceUV[s + 1].x, v);
  33794. uvs.push(faceUV[s + 1].z, v);
  33795. if (hasRings) {
  33796. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33797. }
  33798. else {
  33799. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33800. }
  33801. uvs.push(faceUV[s + 2].x, v);
  33802. uvs.push(faceUV[s + 2].z, v);
  33803. if (faceColors) {
  33804. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33805. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33806. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33807. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33808. }
  33809. }
  33810. if (cs !== s) {
  33811. cs = s;
  33812. }
  33813. }
  33814. }
  33815. // indices
  33816. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33817. var s;
  33818. i = 0;
  33819. for (s = 0; s < subdivisions; s++) {
  33820. var i0 = 0;
  33821. var i1 = 0;
  33822. var i2 = 0;
  33823. var i3 = 0;
  33824. for (j = 0; j < tessellation; j++) {
  33825. i0 = i * (e + 1) + j;
  33826. i1 = (i + 1) * (e + 1) + j;
  33827. i2 = i * (e + 1) + (j + 1);
  33828. i3 = (i + 1) * (e + 1) + (j + 1);
  33829. indices.push(i0, i1, i2);
  33830. indices.push(i3, i2, i1);
  33831. }
  33832. if (arc !== 1 && enclose) {
  33833. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33834. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33835. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33836. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33837. }
  33838. i = (hasRings) ? (i + 2) : (i + 1);
  33839. }
  33840. // Caps
  33841. var createCylinderCap = function (isTop) {
  33842. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33843. if (radius === 0) {
  33844. return;
  33845. }
  33846. // Cap positions, normals & uvs
  33847. var angle;
  33848. var circleVector;
  33849. var i;
  33850. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33851. var c = null;
  33852. if (faceColors) {
  33853. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33854. }
  33855. // cap center
  33856. var vbase = positions.length / 3;
  33857. var offset = isTop ? height / 2 : -height / 2;
  33858. var center = new BABYLON.Vector3(0, offset, 0);
  33859. positions.push(center.x, center.y, center.z);
  33860. normals.push(0, isTop ? 1 : -1, 0);
  33861. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33862. if (c) {
  33863. colors.push(c.r, c.g, c.b, c.a);
  33864. }
  33865. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33866. for (i = 0; i <= tessellation; i++) {
  33867. angle = Math.PI * 2 * i * arc / tessellation;
  33868. var cos = Math.cos(-angle);
  33869. var sin = Math.sin(-angle);
  33870. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33871. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33872. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33873. normals.push(0, isTop ? 1 : -1, 0);
  33874. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33875. if (c) {
  33876. colors.push(c.r, c.g, c.b, c.a);
  33877. }
  33878. }
  33879. // Cap indices
  33880. for (i = 0; i < tessellation; i++) {
  33881. if (!isTop) {
  33882. indices.push(vbase);
  33883. indices.push(vbase + (i + 1));
  33884. indices.push(vbase + (i + 2));
  33885. }
  33886. else {
  33887. indices.push(vbase);
  33888. indices.push(vbase + (i + 2));
  33889. indices.push(vbase + (i + 1));
  33890. }
  33891. }
  33892. };
  33893. // add caps to geometry
  33894. createCylinderCap(false);
  33895. createCylinderCap(true);
  33896. // Sides
  33897. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33898. var vertexData = new VertexData();
  33899. vertexData.indices = indices;
  33900. vertexData.positions = positions;
  33901. vertexData.normals = normals;
  33902. vertexData.uvs = uvs;
  33903. if (faceColors) {
  33904. vertexData.colors = colors;
  33905. }
  33906. return vertexData;
  33907. };
  33908. /**
  33909. * Creates the VertexData of the Torus.
  33910. */
  33911. VertexData.CreateTorus = function (options) {
  33912. var indices = [];
  33913. var positions = [];
  33914. var normals = [];
  33915. var uvs = [];
  33916. var diameter = options.diameter || 1;
  33917. var thickness = options.thickness || 0.5;
  33918. var tessellation = options.tessellation || 16;
  33919. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33920. var stride = tessellation + 1;
  33921. for (var i = 0; i <= tessellation; i++) {
  33922. var u = i / tessellation;
  33923. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33924. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33925. for (var j = 0; j <= tessellation; j++) {
  33926. var v = 1 - j / tessellation;
  33927. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33928. var dx = Math.cos(innerAngle);
  33929. var dy = Math.sin(innerAngle);
  33930. // Create a vertex.
  33931. var normal = new BABYLON.Vector3(dx, dy, 0);
  33932. var position = normal.scale(thickness / 2);
  33933. var textureCoordinate = new BABYLON.Vector2(u, v);
  33934. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33935. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33936. positions.push(position.x, position.y, position.z);
  33937. normals.push(normal.x, normal.y, normal.z);
  33938. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33939. // And create indices for two triangles.
  33940. var nextI = (i + 1) % stride;
  33941. var nextJ = (j + 1) % stride;
  33942. indices.push(i * stride + j);
  33943. indices.push(i * stride + nextJ);
  33944. indices.push(nextI * stride + j);
  33945. indices.push(i * stride + nextJ);
  33946. indices.push(nextI * stride + nextJ);
  33947. indices.push(nextI * stride + j);
  33948. }
  33949. }
  33950. // Sides
  33951. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33952. // Result
  33953. var vertexData = new VertexData();
  33954. vertexData.indices = indices;
  33955. vertexData.positions = positions;
  33956. vertexData.normals = normals;
  33957. vertexData.uvs = uvs;
  33958. return vertexData;
  33959. };
  33960. /**
  33961. * Creates the VertexData of the LineSystem.
  33962. */
  33963. VertexData.CreateLineSystem = function (options) {
  33964. var indices = [];
  33965. var positions = [];
  33966. var lines = options.lines;
  33967. var colors = options.colors;
  33968. var vertexColors = [];
  33969. var idx = 0;
  33970. for (var l = 0; l < lines.length; l++) {
  33971. var points = lines[l];
  33972. for (var index = 0; index < points.length; index++) {
  33973. positions.push(points[index].x, points[index].y, points[index].z);
  33974. if (colors) {
  33975. var color = colors[l];
  33976. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33977. }
  33978. if (index > 0) {
  33979. indices.push(idx - 1);
  33980. indices.push(idx);
  33981. }
  33982. idx++;
  33983. }
  33984. }
  33985. var vertexData = new VertexData();
  33986. vertexData.indices = indices;
  33987. vertexData.positions = positions;
  33988. if (colors) {
  33989. vertexData.colors = vertexColors;
  33990. }
  33991. return vertexData;
  33992. };
  33993. /**
  33994. * Create the VertexData of the DashedLines.
  33995. */
  33996. VertexData.CreateDashedLines = function (options) {
  33997. var dashSize = options.dashSize || 3;
  33998. var gapSize = options.gapSize || 1;
  33999. var dashNb = options.dashNb || 200;
  34000. var points = options.points;
  34001. var positions = new Array();
  34002. var indices = new Array();
  34003. var curvect = BABYLON.Vector3.Zero();
  34004. var lg = 0;
  34005. var nb = 0;
  34006. var shft = 0;
  34007. var dashshft = 0;
  34008. var curshft = 0;
  34009. var idx = 0;
  34010. var i = 0;
  34011. for (i = 0; i < points.length - 1; i++) {
  34012. points[i + 1].subtractToRef(points[i], curvect);
  34013. lg += curvect.length();
  34014. }
  34015. shft = lg / dashNb;
  34016. dashshft = dashSize * shft / (dashSize + gapSize);
  34017. for (i = 0; i < points.length - 1; i++) {
  34018. points[i + 1].subtractToRef(points[i], curvect);
  34019. nb = Math.floor(curvect.length() / shft);
  34020. curvect.normalize();
  34021. for (var j = 0; j < nb; j++) {
  34022. curshft = shft * j;
  34023. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34024. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34025. indices.push(idx, idx + 1);
  34026. idx += 2;
  34027. }
  34028. }
  34029. // Result
  34030. var vertexData = new VertexData();
  34031. vertexData.positions = positions;
  34032. vertexData.indices = indices;
  34033. return vertexData;
  34034. };
  34035. /**
  34036. * Creates the VertexData of the Ground.
  34037. */
  34038. VertexData.CreateGround = function (options) {
  34039. var indices = [];
  34040. var positions = [];
  34041. var normals = [];
  34042. var uvs = [];
  34043. var row, col;
  34044. var width = options.width || 1;
  34045. var height = options.height || 1;
  34046. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34047. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34048. for (row = 0; row <= subdivisionsY; row++) {
  34049. for (col = 0; col <= subdivisionsX; col++) {
  34050. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34051. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34052. positions.push(position.x, position.y, position.z);
  34053. normals.push(normal.x, normal.y, normal.z);
  34054. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34055. }
  34056. }
  34057. for (row = 0; row < subdivisionsY; row++) {
  34058. for (col = 0; col < subdivisionsX; col++) {
  34059. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34060. indices.push(col + 1 + row * (subdivisionsX + 1));
  34061. indices.push(col + row * (subdivisionsX + 1));
  34062. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34063. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34064. indices.push(col + row * (subdivisionsX + 1));
  34065. }
  34066. }
  34067. // Result
  34068. var vertexData = new VertexData();
  34069. vertexData.indices = indices;
  34070. vertexData.positions = positions;
  34071. vertexData.normals = normals;
  34072. vertexData.uvs = uvs;
  34073. return vertexData;
  34074. };
  34075. /**
  34076. * Creates the VertexData of the TiledGround.
  34077. */
  34078. VertexData.CreateTiledGround = function (options) {
  34079. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34080. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34081. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34082. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34083. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34084. var precision = options.precision || { w: 1, h: 1 };
  34085. var indices = new Array();
  34086. var positions = new Array();
  34087. var normals = new Array();
  34088. var uvs = new Array();
  34089. var row, col, tileRow, tileCol;
  34090. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34091. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34092. precision.w = (precision.w < 1) ? 1 : precision.w;
  34093. precision.h = (precision.h < 1) ? 1 : precision.h;
  34094. var tileSize = {
  34095. 'w': (xmax - xmin) / subdivisions.w,
  34096. 'h': (zmax - zmin) / subdivisions.h
  34097. };
  34098. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34099. // Indices
  34100. var base = positions.length / 3;
  34101. var rowLength = precision.w + 1;
  34102. for (row = 0; row < precision.h; row++) {
  34103. for (col = 0; col < precision.w; col++) {
  34104. var square = [
  34105. base + col + row * rowLength,
  34106. base + (col + 1) + row * rowLength,
  34107. base + (col + 1) + (row + 1) * rowLength,
  34108. base + col + (row + 1) * rowLength
  34109. ];
  34110. indices.push(square[1]);
  34111. indices.push(square[2]);
  34112. indices.push(square[3]);
  34113. indices.push(square[0]);
  34114. indices.push(square[1]);
  34115. indices.push(square[3]);
  34116. }
  34117. }
  34118. // Position, normals and uvs
  34119. var position = BABYLON.Vector3.Zero();
  34120. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34121. for (row = 0; row <= precision.h; row++) {
  34122. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34123. for (col = 0; col <= precision.w; col++) {
  34124. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34125. position.y = 0;
  34126. positions.push(position.x, position.y, position.z);
  34127. normals.push(normal.x, normal.y, normal.z);
  34128. uvs.push(col / precision.w, row / precision.h);
  34129. }
  34130. }
  34131. }
  34132. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34133. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34134. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34135. }
  34136. }
  34137. // Result
  34138. var vertexData = new VertexData();
  34139. vertexData.indices = indices;
  34140. vertexData.positions = positions;
  34141. vertexData.normals = normals;
  34142. vertexData.uvs = uvs;
  34143. return vertexData;
  34144. };
  34145. /**
  34146. * Creates the VertexData of the Ground designed from a heightmap.
  34147. */
  34148. VertexData.CreateGroundFromHeightMap = function (options) {
  34149. var indices = [];
  34150. var positions = [];
  34151. var normals = [];
  34152. var uvs = [];
  34153. var row, col;
  34154. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34155. // Vertices
  34156. for (row = 0; row <= options.subdivisions; row++) {
  34157. for (col = 0; col <= options.subdivisions; col++) {
  34158. 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));
  34159. // Compute height
  34160. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34161. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34162. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34163. var r = options.buffer[pos] / 255.0;
  34164. var g = options.buffer[pos + 1] / 255.0;
  34165. var b = options.buffer[pos + 2] / 255.0;
  34166. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34167. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34168. // Add vertex
  34169. positions.push(position.x, position.y, position.z);
  34170. normals.push(0, 0, 0);
  34171. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34172. }
  34173. }
  34174. // Indices
  34175. for (row = 0; row < options.subdivisions; row++) {
  34176. for (col = 0; col < options.subdivisions; col++) {
  34177. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34178. indices.push(col + 1 + row * (options.subdivisions + 1));
  34179. indices.push(col + row * (options.subdivisions + 1));
  34180. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34181. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34182. indices.push(col + row * (options.subdivisions + 1));
  34183. }
  34184. }
  34185. // Normals
  34186. VertexData.ComputeNormals(positions, indices, normals);
  34187. // Result
  34188. var vertexData = new VertexData();
  34189. vertexData.indices = indices;
  34190. vertexData.positions = positions;
  34191. vertexData.normals = normals;
  34192. vertexData.uvs = uvs;
  34193. return vertexData;
  34194. };
  34195. /**
  34196. * Creates the VertexData of the Plane.
  34197. */
  34198. VertexData.CreatePlane = function (options) {
  34199. var indices = [];
  34200. var positions = [];
  34201. var normals = [];
  34202. var uvs = [];
  34203. var width = options.width || options.size || 1;
  34204. var height = options.height || options.size || 1;
  34205. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34206. // Vertices
  34207. var halfWidth = width / 2.0;
  34208. var halfHeight = height / 2.0;
  34209. positions.push(-halfWidth, -halfHeight, 0);
  34210. normals.push(0, 0, -1.0);
  34211. uvs.push(0.0, 0.0);
  34212. positions.push(halfWidth, -halfHeight, 0);
  34213. normals.push(0, 0, -1.0);
  34214. uvs.push(1.0, 0.0);
  34215. positions.push(halfWidth, halfHeight, 0);
  34216. normals.push(0, 0, -1.0);
  34217. uvs.push(1.0, 1.0);
  34218. positions.push(-halfWidth, halfHeight, 0);
  34219. normals.push(0, 0, -1.0);
  34220. uvs.push(0.0, 1.0);
  34221. // Indices
  34222. indices.push(0);
  34223. indices.push(1);
  34224. indices.push(2);
  34225. indices.push(0);
  34226. indices.push(2);
  34227. indices.push(3);
  34228. // Sides
  34229. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34230. // Result
  34231. var vertexData = new VertexData();
  34232. vertexData.indices = indices;
  34233. vertexData.positions = positions;
  34234. vertexData.normals = normals;
  34235. vertexData.uvs = uvs;
  34236. return vertexData;
  34237. };
  34238. /**
  34239. * Creates the VertexData of the Disc or regular Polygon.
  34240. */
  34241. VertexData.CreateDisc = function (options) {
  34242. var positions = new Array();
  34243. var indices = new Array();
  34244. var normals = new Array();
  34245. var uvs = new Array();
  34246. var radius = options.radius || 0.5;
  34247. var tessellation = options.tessellation || 64;
  34248. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34249. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34250. // positions and uvs
  34251. positions.push(0, 0, 0); // disc center first
  34252. uvs.push(0.5, 0.5);
  34253. var theta = Math.PI * 2 * arc;
  34254. var step = theta / tessellation;
  34255. for (var a = 0; a < theta; a += step) {
  34256. var x = Math.cos(a);
  34257. var y = Math.sin(a);
  34258. var u = (x + 1) / 2;
  34259. var v = (1 - y) / 2;
  34260. positions.push(radius * x, radius * y, 0);
  34261. uvs.push(u, v);
  34262. }
  34263. if (arc === 1) {
  34264. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34265. uvs.push(uvs[2], uvs[3]);
  34266. }
  34267. //indices
  34268. var vertexNb = positions.length / 3;
  34269. for (var i = 1; i < vertexNb - 1; i++) {
  34270. indices.push(i + 1, 0, i);
  34271. }
  34272. // result
  34273. VertexData.ComputeNormals(positions, indices, normals);
  34274. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34275. var vertexData = new VertexData();
  34276. vertexData.indices = indices;
  34277. vertexData.positions = positions;
  34278. vertexData.normals = normals;
  34279. vertexData.uvs = uvs;
  34280. return vertexData;
  34281. };
  34282. /**
  34283. * Re-creates the VertexData of the Polygon for sideOrientation.
  34284. */
  34285. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34286. var faceUV = fUV || new Array(3);
  34287. var faceColors = fColors;
  34288. var colors = [];
  34289. // default face colors and UV if undefined
  34290. for (var f = 0; f < 3; f++) {
  34291. if (faceUV[f] === undefined) {
  34292. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34293. }
  34294. if (faceColors && faceColors[f] === undefined) {
  34295. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34296. }
  34297. }
  34298. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34299. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34300. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34301. var indices = polygon.getIndices();
  34302. // set face colours and textures
  34303. var idx = 0;
  34304. var face = 0;
  34305. for (var index = 0; index < normals.length; index += 3) {
  34306. //Edge Face no. 1
  34307. if (Math.abs(normals[index + 1]) < 0.001) {
  34308. face = 1;
  34309. }
  34310. //Top Face no. 0
  34311. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34312. face = 0;
  34313. }
  34314. //Bottom Face no. 2
  34315. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34316. face = 2;
  34317. }
  34318. idx = index / 3;
  34319. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34320. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34321. if (faceColors) {
  34322. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34323. }
  34324. }
  34325. // sides
  34326. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34327. // Result
  34328. var vertexData = new VertexData();
  34329. vertexData.indices = indices;
  34330. vertexData.positions = positions;
  34331. vertexData.normals = normals;
  34332. vertexData.uvs = uvs;
  34333. if (faceColors) {
  34334. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34335. vertexData.colors = totalColors;
  34336. }
  34337. return vertexData;
  34338. };
  34339. /**
  34340. * Creates the VertexData of the IcoSphere.
  34341. */
  34342. VertexData.CreateIcoSphere = function (options) {
  34343. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34344. var radius = options.radius || 1;
  34345. var flat = (options.flat === undefined) ? true : options.flat;
  34346. var subdivisions = options.subdivisions || 4;
  34347. var radiusX = options.radiusX || radius;
  34348. var radiusY = options.radiusY || radius;
  34349. var radiusZ = options.radiusZ || radius;
  34350. var t = (1 + Math.sqrt(5)) / 2;
  34351. // 12 vertex x,y,z
  34352. var ico_vertices = [
  34353. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34354. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34355. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34356. ];
  34357. // index of 3 vertex makes a face of icopshere
  34358. var ico_indices = [
  34359. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34360. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34361. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34362. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34363. ];
  34364. // vertex for uv have aliased position, not for UV
  34365. var vertices_unalias_id = [
  34366. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34367. // vertex alias
  34368. 0,
  34369. 2,
  34370. 3,
  34371. 3,
  34372. 3,
  34373. 4,
  34374. 7,
  34375. 8,
  34376. 9,
  34377. 9,
  34378. 10,
  34379. 11 // 23: B + 12
  34380. ];
  34381. // uv as integer step (not pixels !)
  34382. var ico_vertexuv = [
  34383. 5, 1, 3, 1, 6, 4, 0, 0,
  34384. 5, 3, 4, 2, 2, 2, 4, 0,
  34385. 2, 0, 1, 1, 6, 0, 6, 2,
  34386. // vertex alias (for same vertex on different faces)
  34387. 0, 4,
  34388. 3, 3,
  34389. 4, 4,
  34390. 3, 1,
  34391. 4, 2,
  34392. 4, 4,
  34393. 0, 2,
  34394. 1, 1,
  34395. 2, 2,
  34396. 3, 3,
  34397. 1, 3,
  34398. 2, 4 // 23: B + 12
  34399. ];
  34400. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34401. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34402. // First island of uv mapping
  34403. // v = 4h 3+ 2
  34404. // v = 3h 9+ 4
  34405. // v = 2h 9+ 5 B
  34406. // v = 1h 9 1 0
  34407. // v = 0h 3 8 7 A
  34408. // u = 0 1 2 3 4 5 6 *a
  34409. // Second island of uv mapping
  34410. // v = 4h 0+ B+ 4+
  34411. // v = 3h A+ 2+
  34412. // v = 2h 7+ 6 3+
  34413. // v = 1h 8+ 3+
  34414. // v = 0h
  34415. // u = 0 1 2 3 4 5 6 *a
  34416. // Face layout on texture UV mapping
  34417. // ============
  34418. // \ 4 /\ 16 / ======
  34419. // \ / \ / /\ 11 /
  34420. // \/ 7 \/ / \ /
  34421. // ======= / 10 \/
  34422. // /\ 17 /\ =======
  34423. // / \ / \ \ 15 /\
  34424. // / 8 \/ 12 \ \ / \
  34425. // ============ \/ 6 \
  34426. // \ 18 /\ ============
  34427. // \ / \ \ 5 /\ 0 /
  34428. // \/ 13 \ \ / \ /
  34429. // ======= \/ 1 \/
  34430. // =============
  34431. // /\ 19 /\ 2 /\
  34432. // / \ / \ / \
  34433. // / 14 \/ 9 \/ 3 \
  34434. // ===================
  34435. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34436. var ustep = 138 / 1024;
  34437. var vstep = 239 / 1024;
  34438. var uoffset = 60 / 1024;
  34439. var voffset = 26 / 1024;
  34440. // Second island should have margin, not to touch the first island
  34441. // avoid any borderline artefact in pixel rounding
  34442. var island_u_offset = -40 / 1024;
  34443. var island_v_offset = +20 / 1024;
  34444. // face is either island 0 or 1 :
  34445. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34446. var island = [
  34447. 0, 0, 0, 0, 1,
  34448. 0, 0, 1, 1, 0,
  34449. 0, 0, 1, 1, 0,
  34450. 0, 1, 1, 1, 0 // 15 - 19
  34451. ];
  34452. var indices = new Array();
  34453. var positions = new Array();
  34454. var normals = new Array();
  34455. var uvs = new Array();
  34456. var current_indice = 0;
  34457. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34458. var face_vertex_pos = new Array(3);
  34459. var face_vertex_uv = new Array(3);
  34460. var v012;
  34461. for (v012 = 0; v012 < 3; v012++) {
  34462. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34463. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34464. }
  34465. // create all with normals
  34466. for (var face = 0; face < 20; face++) {
  34467. // 3 vertex per face
  34468. for (v012 = 0; v012 < 3; v012++) {
  34469. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34470. var v_id = ico_indices[3 * face + v012];
  34471. // vertex have 3D position (x,y,z)
  34472. 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]);
  34473. // Normalize to get normal, then scale to radius
  34474. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34475. // uv Coordinates from vertex ID
  34476. 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);
  34477. }
  34478. // Subdivide the face (interpolate pos, norm, uv)
  34479. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34480. // - norm is linear interpolation of vertex corner normal
  34481. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34482. // - uv is linear interpolation
  34483. //
  34484. // Topology is as below for sub-divide by 2
  34485. // vertex shown as v0,v1,v2
  34486. // interp index is i1 to progress in range [v0,v1[
  34487. // interp index is i2 to progress in range [v0,v2[
  34488. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34489. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34490. //
  34491. //
  34492. // i2 v2
  34493. // ^ ^
  34494. // / / \
  34495. // / / \
  34496. // / / \
  34497. // / / (0,1) \
  34498. // / #---------\
  34499. // / / \ (0,0)'/ \
  34500. // / / \ / \
  34501. // / / \ / \
  34502. // / / (0,0) \ / (1,0) \
  34503. // / #---------#---------\
  34504. // v0 v1
  34505. //
  34506. // --------------------> i1
  34507. //
  34508. // interp of (i1,i2):
  34509. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34510. // along i1 : lerp(x0,x1, i1/(S-i2))
  34511. //
  34512. // centroid of triangle is needed to get help normal computation
  34513. // (c1,c2) are used for centroid location
  34514. var interp_vertex = function (i1, i2, c1, c2) {
  34515. // vertex is interpolated from
  34516. // - face_vertex_pos[0..2]
  34517. // - face_vertex_uv[0..2]
  34518. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34519. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34520. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34521. pos_interp.normalize();
  34522. var vertex_normal;
  34523. if (flat) {
  34524. // in flat mode, recalculate normal as face centroid normal
  34525. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34526. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34527. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34528. }
  34529. else {
  34530. // in smooth mode, recalculate normal from each single vertex position
  34531. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34532. }
  34533. // Vertex normal need correction due to X,Y,Z radius scaling
  34534. vertex_normal.x /= radiusX;
  34535. vertex_normal.y /= radiusY;
  34536. vertex_normal.z /= radiusZ;
  34537. vertex_normal.normalize();
  34538. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34539. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34540. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34541. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34542. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34543. uvs.push(uv_interp.x, uv_interp.y);
  34544. // push each vertex has member of a face
  34545. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34546. indices.push(current_indice);
  34547. current_indice++;
  34548. };
  34549. for (var i2 = 0; i2 < subdivisions; i2++) {
  34550. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34551. // face : (i1,i2) for /\ :
  34552. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34553. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34554. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34555. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34556. if (i1 + i2 + 1 < subdivisions) {
  34557. // face : (i1,i2)' for \/ :
  34558. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34559. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34560. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34561. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34562. }
  34563. }
  34564. }
  34565. }
  34566. // Sides
  34567. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34568. // Result
  34569. var vertexData = new VertexData();
  34570. vertexData.indices = indices;
  34571. vertexData.positions = positions;
  34572. vertexData.normals = normals;
  34573. vertexData.uvs = uvs;
  34574. return vertexData;
  34575. };
  34576. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34577. /**
  34578. * Creates the VertexData of the Polyhedron.
  34579. */
  34580. VertexData.CreatePolyhedron = function (options) {
  34581. // provided polyhedron types :
  34582. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34583. // 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)
  34584. var polyhedra = [];
  34585. 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]] };
  34586. 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]] };
  34587. polyhedra[2] = {
  34588. 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]],
  34589. 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]]
  34590. };
  34591. polyhedra[3] = {
  34592. 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]],
  34593. 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]]
  34594. };
  34595. polyhedra[4] = {
  34596. 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]],
  34597. 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]]
  34598. };
  34599. 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]] };
  34600. 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]] };
  34601. 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]] };
  34602. 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]] };
  34603. 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]] };
  34604. 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]] };
  34605. 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]] };
  34606. 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]] };
  34607. 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]] };
  34608. polyhedra[14] = {
  34609. 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]],
  34610. 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]]
  34611. };
  34612. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34613. var size = options.size;
  34614. var sizeX = options.sizeX || size || 1;
  34615. var sizeY = options.sizeY || size || 1;
  34616. var sizeZ = options.sizeZ || size || 1;
  34617. var data = options.custom || polyhedra[type];
  34618. var nbfaces = data.face.length;
  34619. var faceUV = options.faceUV || new Array(nbfaces);
  34620. var faceColors = options.faceColors;
  34621. var flat = (options.flat === undefined) ? true : options.flat;
  34622. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34623. var positions = new Array();
  34624. var indices = new Array();
  34625. var normals = new Array();
  34626. var uvs = new Array();
  34627. var colors = new Array();
  34628. var index = 0;
  34629. var faceIdx = 0; // face cursor in the array "indexes"
  34630. var indexes = new Array();
  34631. var i = 0;
  34632. var f = 0;
  34633. var u, v, ang, x, y, tmp;
  34634. // default face colors and UV if undefined
  34635. if (flat) {
  34636. for (f = 0; f < nbfaces; f++) {
  34637. if (faceColors && faceColors[f] === undefined) {
  34638. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34639. }
  34640. if (faceUV && faceUV[f] === undefined) {
  34641. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34642. }
  34643. }
  34644. }
  34645. if (!flat) {
  34646. for (i = 0; i < data.vertex.length; i++) {
  34647. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34648. uvs.push(0, 0);
  34649. }
  34650. for (f = 0; f < nbfaces; f++) {
  34651. for (i = 0; i < data.face[f].length - 2; i++) {
  34652. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34653. }
  34654. }
  34655. }
  34656. else {
  34657. for (f = 0; f < nbfaces; f++) {
  34658. var fl = data.face[f].length; // number of vertices of the current face
  34659. ang = 2 * Math.PI / fl;
  34660. x = 0.5 * Math.tan(ang / 2);
  34661. y = 0.5;
  34662. // positions, uvs, colors
  34663. for (i = 0; i < fl; i++) {
  34664. // positions
  34665. 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);
  34666. indexes.push(index);
  34667. index++;
  34668. // uvs
  34669. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34670. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34671. uvs.push(u, v);
  34672. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34673. y = x * Math.sin(ang) + y * Math.cos(ang);
  34674. x = tmp;
  34675. // colors
  34676. if (faceColors) {
  34677. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34678. }
  34679. }
  34680. // indices from indexes
  34681. for (i = 0; i < fl - 2; i++) {
  34682. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34683. }
  34684. faceIdx += fl;
  34685. }
  34686. }
  34687. VertexData.ComputeNormals(positions, indices, normals);
  34688. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34689. var vertexData = new VertexData();
  34690. vertexData.positions = positions;
  34691. vertexData.indices = indices;
  34692. vertexData.normals = normals;
  34693. vertexData.uvs = uvs;
  34694. if (faceColors && flat) {
  34695. vertexData.colors = colors;
  34696. }
  34697. return vertexData;
  34698. };
  34699. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34700. /**
  34701. * Creates the VertexData of the Torus Knot.
  34702. */
  34703. VertexData.CreateTorusKnot = function (options) {
  34704. var indices = new Array();
  34705. var positions = new Array();
  34706. var normals = new Array();
  34707. var uvs = new Array();
  34708. var radius = options.radius || 2;
  34709. var tube = options.tube || 0.5;
  34710. var radialSegments = options.radialSegments || 32;
  34711. var tubularSegments = options.tubularSegments || 32;
  34712. var p = options.p || 2;
  34713. var q = options.q || 3;
  34714. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34715. // Helper
  34716. var getPos = function (angle) {
  34717. var cu = Math.cos(angle);
  34718. var su = Math.sin(angle);
  34719. var quOverP = q / p * angle;
  34720. var cs = Math.cos(quOverP);
  34721. var tx = radius * (2 + cs) * 0.5 * cu;
  34722. var ty = radius * (2 + cs) * su * 0.5;
  34723. var tz = radius * Math.sin(quOverP) * 0.5;
  34724. return new BABYLON.Vector3(tx, ty, tz);
  34725. };
  34726. // Vertices
  34727. var i;
  34728. var j;
  34729. for (i = 0; i <= radialSegments; i++) {
  34730. var modI = i % radialSegments;
  34731. var u = modI / radialSegments * 2 * p * Math.PI;
  34732. var p1 = getPos(u);
  34733. var p2 = getPos(u + 0.01);
  34734. var tang = p2.subtract(p1);
  34735. var n = p2.add(p1);
  34736. var bitan = BABYLON.Vector3.Cross(tang, n);
  34737. n = BABYLON.Vector3.Cross(bitan, tang);
  34738. bitan.normalize();
  34739. n.normalize();
  34740. for (j = 0; j < tubularSegments; j++) {
  34741. var modJ = j % tubularSegments;
  34742. var v = modJ / tubularSegments * 2 * Math.PI;
  34743. var cx = -tube * Math.cos(v);
  34744. var cy = tube * Math.sin(v);
  34745. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34746. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34747. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34748. uvs.push(i / radialSegments);
  34749. uvs.push(j / tubularSegments);
  34750. }
  34751. }
  34752. for (i = 0; i < radialSegments; i++) {
  34753. for (j = 0; j < tubularSegments; j++) {
  34754. var jNext = (j + 1) % tubularSegments;
  34755. var a = i * tubularSegments + j;
  34756. var b = (i + 1) * tubularSegments + j;
  34757. var c = (i + 1) * tubularSegments + jNext;
  34758. var d = i * tubularSegments + jNext;
  34759. indices.push(d);
  34760. indices.push(b);
  34761. indices.push(a);
  34762. indices.push(d);
  34763. indices.push(c);
  34764. indices.push(b);
  34765. }
  34766. }
  34767. // Normals
  34768. VertexData.ComputeNormals(positions, indices, normals);
  34769. // Sides
  34770. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34771. // Result
  34772. var vertexData = new VertexData();
  34773. vertexData.indices = indices;
  34774. vertexData.positions = positions;
  34775. vertexData.normals = normals;
  34776. vertexData.uvs = uvs;
  34777. return vertexData;
  34778. };
  34779. // Tools
  34780. /**
  34781. * @param {any} - positions (number[] or Float32Array)
  34782. * @param {any} - indices (number[] or Uint16Array)
  34783. * @param {any} - normals (number[] or Float32Array)
  34784. * options (optional) :
  34785. * facetPositions : optional array of facet positions (vector3)
  34786. * facetNormals : optional array of facet normals (vector3)
  34787. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34788. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34789. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34790. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34791. * bInfo : optional bounding info, required for facetPartitioning computation
  34792. * useRightHandedSystem: optional boolean to for right handed system computation
  34793. * depthSort : optional boolean to enable the facet depth sort computation
  34794. * distanceTo : optional Vector3 to compute the facet depth from this location
  34795. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34796. */
  34797. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34798. // temporary scalar variables
  34799. var index = 0; // facet index
  34800. var p1p2x = 0.0; // p1p2 vector x coordinate
  34801. var p1p2y = 0.0; // p1p2 vector y coordinate
  34802. var p1p2z = 0.0; // p1p2 vector z coordinate
  34803. var p3p2x = 0.0; // p3p2 vector x coordinate
  34804. var p3p2y = 0.0; // p3p2 vector y coordinate
  34805. var p3p2z = 0.0; // p3p2 vector z coordinate
  34806. var faceNormalx = 0.0; // facet normal x coordinate
  34807. var faceNormaly = 0.0; // facet normal y coordinate
  34808. var faceNormalz = 0.0; // facet normal z coordinate
  34809. var length = 0.0; // facet normal length before normalization
  34810. var v1x = 0; // vector1 x index in the positions array
  34811. var v1y = 0; // vector1 y index in the positions array
  34812. var v1z = 0; // vector1 z index in the positions array
  34813. var v2x = 0; // vector2 x index in the positions array
  34814. var v2y = 0; // vector2 y index in the positions array
  34815. var v2z = 0; // vector2 z index in the positions array
  34816. var v3x = 0; // vector3 x index in the positions array
  34817. var v3y = 0; // vector3 y index in the positions array
  34818. var v3z = 0; // vector3 z index in the positions array
  34819. var computeFacetNormals = false;
  34820. var computeFacetPositions = false;
  34821. var computeFacetPartitioning = false;
  34822. var computeDepthSort = false;
  34823. var faceNormalSign = 1;
  34824. var ratio = 0;
  34825. var distanceTo = null;
  34826. if (options) {
  34827. computeFacetNormals = (options.facetNormals) ? true : false;
  34828. computeFacetPositions = (options.facetPositions) ? true : false;
  34829. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34830. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34831. ratio = options.ratio || 0;
  34832. computeDepthSort = (options.depthSort) ? true : false;
  34833. distanceTo = (options.distanceTo);
  34834. if (computeDepthSort) {
  34835. if (distanceTo === undefined) {
  34836. distanceTo = BABYLON.Vector3.Zero();
  34837. }
  34838. var depthSortedFacets = options.depthSortedFacets;
  34839. }
  34840. }
  34841. // facetPartitioning reinit if needed
  34842. var xSubRatio = 0;
  34843. var ySubRatio = 0;
  34844. var zSubRatio = 0;
  34845. var subSq = 0;
  34846. if (computeFacetPartitioning && options && options.bbSize) {
  34847. var ox = 0; // X partitioning index for facet position
  34848. var oy = 0; // Y partinioning index for facet position
  34849. var oz = 0; // Z partinioning index for facet position
  34850. var b1x = 0; // X partitioning index for facet v1 vertex
  34851. var b1y = 0; // Y partitioning index for facet v1 vertex
  34852. var b1z = 0; // z partitioning index for facet v1 vertex
  34853. var b2x = 0; // X partitioning index for facet v2 vertex
  34854. var b2y = 0; // Y partitioning index for facet v2 vertex
  34855. var b2z = 0; // Z partitioning index for facet v2 vertex
  34856. var b3x = 0; // X partitioning index for facet v3 vertex
  34857. var b3y = 0; // Y partitioning index for facet v3 vertex
  34858. var b3z = 0; // Z partitioning index for facet v3 vertex
  34859. var block_idx_o = 0; // facet barycenter block index
  34860. var block_idx_v1 = 0; // v1 vertex block index
  34861. var block_idx_v2 = 0; // v2 vertex block index
  34862. var block_idx_v3 = 0; // v3 vertex block index
  34863. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34864. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34865. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34866. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34867. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34868. subSq = options.subDiv.max * options.subDiv.max;
  34869. options.facetPartitioning.length = 0;
  34870. }
  34871. // reset the normals
  34872. for (index = 0; index < positions.length; index++) {
  34873. normals[index] = 0.0;
  34874. }
  34875. // Loop : 1 indice triplet = 1 facet
  34876. var nbFaces = (indices.length / 3) | 0;
  34877. for (index = 0; index < nbFaces; index++) {
  34878. // get the indexes of the coordinates of each vertex of the facet
  34879. v1x = indices[index * 3] * 3;
  34880. v1y = v1x + 1;
  34881. v1z = v1x + 2;
  34882. v2x = indices[index * 3 + 1] * 3;
  34883. v2y = v2x + 1;
  34884. v2z = v2x + 2;
  34885. v3x = indices[index * 3 + 2] * 3;
  34886. v3y = v3x + 1;
  34887. v3z = v3x + 2;
  34888. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34889. p1p2y = positions[v1y] - positions[v2y];
  34890. p1p2z = positions[v1z] - positions[v2z];
  34891. p3p2x = positions[v3x] - positions[v2x];
  34892. p3p2y = positions[v3y] - positions[v2y];
  34893. p3p2z = positions[v3z] - positions[v2z];
  34894. // compute the face normal with the cross product
  34895. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34896. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34897. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34898. // normalize this normal and store it in the array facetData
  34899. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34900. length = (length === 0) ? 1.0 : length;
  34901. faceNormalx /= length;
  34902. faceNormaly /= length;
  34903. faceNormalz /= length;
  34904. if (computeFacetNormals && options) {
  34905. options.facetNormals[index].x = faceNormalx;
  34906. options.facetNormals[index].y = faceNormaly;
  34907. options.facetNormals[index].z = faceNormalz;
  34908. }
  34909. if (computeFacetPositions && options) {
  34910. // compute and the facet barycenter coordinates in the array facetPositions
  34911. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34912. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34913. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34914. }
  34915. if (computeFacetPartitioning && options) {
  34916. // store the facet indexes in arrays in the main facetPartitioning array :
  34917. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34918. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34919. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34920. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34921. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34922. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34923. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34924. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34925. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34926. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34927. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34928. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34929. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34930. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34931. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34932. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34933. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34934. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34935. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34936. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34937. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34938. // push each facet index in each block containing the vertex
  34939. options.facetPartitioning[block_idx_v1].push(index);
  34940. if (block_idx_v2 != block_idx_v1) {
  34941. options.facetPartitioning[block_idx_v2].push(index);
  34942. }
  34943. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34944. options.facetPartitioning[block_idx_v3].push(index);
  34945. }
  34946. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34947. options.facetPartitioning[block_idx_o].push(index);
  34948. }
  34949. }
  34950. if (computeDepthSort && options && options.facetPositions) {
  34951. var dsf = depthSortedFacets[index];
  34952. dsf.ind = index * 3;
  34953. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34954. }
  34955. // compute the normals anyway
  34956. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34957. normals[v1y] += faceNormaly;
  34958. normals[v1z] += faceNormalz;
  34959. normals[v2x] += faceNormalx;
  34960. normals[v2y] += faceNormaly;
  34961. normals[v2z] += faceNormalz;
  34962. normals[v3x] += faceNormalx;
  34963. normals[v3y] += faceNormaly;
  34964. normals[v3z] += faceNormalz;
  34965. }
  34966. // last normalization of each normal
  34967. for (index = 0; index < normals.length / 3; index++) {
  34968. faceNormalx = normals[index * 3];
  34969. faceNormaly = normals[index * 3 + 1];
  34970. faceNormalz = normals[index * 3 + 2];
  34971. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34972. length = (length === 0) ? 1.0 : length;
  34973. faceNormalx /= length;
  34974. faceNormaly /= length;
  34975. faceNormalz /= length;
  34976. normals[index * 3] = faceNormalx;
  34977. normals[index * 3 + 1] = faceNormaly;
  34978. normals[index * 3 + 2] = faceNormalz;
  34979. }
  34980. };
  34981. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34982. var li = indices.length;
  34983. var ln = normals.length;
  34984. var i;
  34985. var n;
  34986. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34987. switch (sideOrientation) {
  34988. case BABYLON.Mesh.FRONTSIDE:
  34989. // nothing changed
  34990. break;
  34991. case BABYLON.Mesh.BACKSIDE:
  34992. var tmp;
  34993. // indices
  34994. for (i = 0; i < li; i += 3) {
  34995. tmp = indices[i];
  34996. indices[i] = indices[i + 2];
  34997. indices[i + 2] = tmp;
  34998. }
  34999. // normals
  35000. for (n = 0; n < ln; n++) {
  35001. normals[n] = -normals[n];
  35002. }
  35003. break;
  35004. case BABYLON.Mesh.DOUBLESIDE:
  35005. // positions
  35006. var lp = positions.length;
  35007. var l = lp / 3;
  35008. for (var p = 0; p < lp; p++) {
  35009. positions[lp + p] = positions[p];
  35010. }
  35011. // indices
  35012. for (i = 0; i < li; i += 3) {
  35013. indices[i + li] = indices[i + 2] + l;
  35014. indices[i + 1 + li] = indices[i + 1] + l;
  35015. indices[i + 2 + li] = indices[i] + l;
  35016. }
  35017. // normals
  35018. for (n = 0; n < ln; n++) {
  35019. normals[ln + n] = -normals[n];
  35020. }
  35021. // uvs
  35022. var lu = uvs.length;
  35023. var u = 0;
  35024. for (u = 0; u < lu; u++) {
  35025. uvs[u + lu] = uvs[u];
  35026. }
  35027. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35028. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35029. u = 0;
  35030. for (i = 0; i < lu / 2; i++) {
  35031. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35032. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35033. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35034. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35035. u += 2;
  35036. }
  35037. break;
  35038. }
  35039. };
  35040. /**
  35041. * Creates a new VertexData from the imported parameters.
  35042. */
  35043. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35044. var vertexData = new VertexData();
  35045. // positions
  35046. var positions = parsedVertexData.positions;
  35047. if (positions) {
  35048. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35049. }
  35050. // normals
  35051. var normals = parsedVertexData.normals;
  35052. if (normals) {
  35053. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35054. }
  35055. // tangents
  35056. var tangents = parsedVertexData.tangents;
  35057. if (tangents) {
  35058. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35059. }
  35060. // uvs
  35061. var uvs = parsedVertexData.uvs;
  35062. if (uvs) {
  35063. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35064. }
  35065. // uv2s
  35066. var uv2s = parsedVertexData.uv2s;
  35067. if (uv2s) {
  35068. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35069. }
  35070. // uv3s
  35071. var uv3s = parsedVertexData.uv3s;
  35072. if (uv3s) {
  35073. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35074. }
  35075. // uv4s
  35076. var uv4s = parsedVertexData.uv4s;
  35077. if (uv4s) {
  35078. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35079. }
  35080. // uv5s
  35081. var uv5s = parsedVertexData.uv5s;
  35082. if (uv5s) {
  35083. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35084. }
  35085. // uv6s
  35086. var uv6s = parsedVertexData.uv6s;
  35087. if (uv6s) {
  35088. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35089. }
  35090. // colors
  35091. var colors = parsedVertexData.colors;
  35092. if (colors) {
  35093. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35094. }
  35095. // matricesIndices
  35096. var matricesIndices = parsedVertexData.matricesIndices;
  35097. if (matricesIndices) {
  35098. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35099. }
  35100. // matricesWeights
  35101. var matricesWeights = parsedVertexData.matricesWeights;
  35102. if (matricesWeights) {
  35103. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35104. }
  35105. // indices
  35106. var indices = parsedVertexData.indices;
  35107. if (indices) {
  35108. vertexData.indices = indices;
  35109. }
  35110. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35111. };
  35112. return VertexData;
  35113. }());
  35114. BABYLON.VertexData = VertexData;
  35115. })(BABYLON || (BABYLON = {}));
  35116. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35117. "use strict";
  35118. var BABYLON;
  35119. (function (BABYLON) {
  35120. /**
  35121. * Class used to store geometry data (vertex buffers + index buffer)
  35122. */
  35123. var Geometry = /** @class */ (function () {
  35124. /**
  35125. * Creates a new geometry
  35126. * @param id defines the unique ID
  35127. * @param scene defines the hosting scene
  35128. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35129. * @param updatable defines if geometry must be updatable (false by default)
  35130. * @param mesh defines the mesh that will be associated with the geometry
  35131. */
  35132. function Geometry(id, scene, vertexData, updatable, mesh) {
  35133. if (updatable === void 0) { updatable = false; }
  35134. if (mesh === void 0) { mesh = null; }
  35135. /**
  35136. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35137. */
  35138. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35139. this._totalVertices = 0;
  35140. this._isDisposed = false;
  35141. this._indexBufferIsUpdatable = false;
  35142. this.id = id;
  35143. this._engine = scene.getEngine();
  35144. this._meshes = [];
  35145. this._scene = scene;
  35146. //Init vertex buffer cache
  35147. this._vertexBuffers = {};
  35148. this._indices = [];
  35149. this._updatable = updatable;
  35150. // vertexData
  35151. if (vertexData) {
  35152. this.setAllVerticesData(vertexData, updatable);
  35153. }
  35154. else {
  35155. this._totalVertices = 0;
  35156. this._indices = [];
  35157. }
  35158. if (this._engine.getCaps().vertexArrayObject) {
  35159. this._vertexArrayObjects = {};
  35160. }
  35161. // applyToMesh
  35162. if (mesh) {
  35163. if (mesh.getClassName() === "LinesMesh") {
  35164. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35165. this.updateExtend();
  35166. }
  35167. this.applyToMesh(mesh);
  35168. mesh.computeWorldMatrix(true);
  35169. }
  35170. }
  35171. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35172. /**
  35173. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  35174. */
  35175. get: function () {
  35176. return this._boundingBias;
  35177. },
  35178. /**
  35179. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  35180. */
  35181. set: function (value) {
  35182. if (this._boundingBias && this._boundingBias.equals(value)) {
  35183. return;
  35184. }
  35185. this._boundingBias = value.clone();
  35186. this.updateBoundingInfo(true, null);
  35187. },
  35188. enumerable: true,
  35189. configurable: true
  35190. });
  35191. /**
  35192. * Static function used to attach a new empty geometry to a mesh
  35193. * @param mesh defines the mesh to attach the geometry to
  35194. * @returns the new {BABYLON.Geometry}
  35195. */
  35196. Geometry.CreateGeometryForMesh = function (mesh) {
  35197. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35198. geometry.applyToMesh(mesh);
  35199. return geometry;
  35200. };
  35201. Object.defineProperty(Geometry.prototype, "extend", {
  35202. /**
  35203. * Gets the current extend of the geometry
  35204. */
  35205. get: function () {
  35206. return this._extend;
  35207. },
  35208. enumerable: true,
  35209. configurable: true
  35210. });
  35211. /**
  35212. * Gets the hosting scene
  35213. * @returns the hosting {BABYLON.Scene}
  35214. */
  35215. Geometry.prototype.getScene = function () {
  35216. return this._scene;
  35217. };
  35218. /**
  35219. * Gets the hosting engine
  35220. * @returns the hosting {BABYLON.Engine}
  35221. */
  35222. Geometry.prototype.getEngine = function () {
  35223. return this._engine;
  35224. };
  35225. /**
  35226. * Defines if the geometry is ready to use
  35227. * @returns true if the geometry is ready to be used
  35228. */
  35229. Geometry.prototype.isReady = function () {
  35230. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35231. };
  35232. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35233. /**
  35234. * Gets a value indicating that the geometry should not be serialized
  35235. */
  35236. get: function () {
  35237. for (var index = 0; index < this._meshes.length; index++) {
  35238. if (!this._meshes[index].doNotSerialize) {
  35239. return false;
  35240. }
  35241. }
  35242. return true;
  35243. },
  35244. enumerable: true,
  35245. configurable: true
  35246. });
  35247. /** @ignore */
  35248. Geometry.prototype._rebuild = function () {
  35249. if (this._vertexArrayObjects) {
  35250. this._vertexArrayObjects = {};
  35251. }
  35252. // Index buffer
  35253. if (this._meshes.length !== 0 && this._indices) {
  35254. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35255. }
  35256. // Vertex buffers
  35257. for (var key in this._vertexBuffers) {
  35258. var vertexBuffer = this._vertexBuffers[key];
  35259. vertexBuffer._rebuild();
  35260. }
  35261. };
  35262. /**
  35263. * Affects all gemetry data in one call
  35264. * @param vertexData defines the geometry data
  35265. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35266. */
  35267. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35268. vertexData.applyToGeometry(this, updatable);
  35269. this.notifyUpdate();
  35270. };
  35271. /**
  35272. * Set specific vertex data
  35273. * @param kind defines the data kind (Position, normal, etc...)
  35274. * @param data defines the vertex data to use
  35275. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35276. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35277. */
  35278. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35279. if (updatable === void 0) { updatable = false; }
  35280. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35281. this.setVerticesBuffer(buffer);
  35282. };
  35283. /**
  35284. * Removes a specific vertex data
  35285. * @param kind defines the data kind (Position, normal, etc...)
  35286. */
  35287. Geometry.prototype.removeVerticesData = function (kind) {
  35288. if (this._vertexBuffers[kind]) {
  35289. this._vertexBuffers[kind].dispose();
  35290. delete this._vertexBuffers[kind];
  35291. }
  35292. };
  35293. /**
  35294. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35295. * @param buffer defines the vertex buffer to use
  35296. */
  35297. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35298. var kind = buffer.getKind();
  35299. if (this._vertexBuffers[kind]) {
  35300. this._vertexBuffers[kind].dispose();
  35301. }
  35302. this._vertexBuffers[kind] = buffer;
  35303. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35304. var data = buffer.getData();
  35305. var stride = buffer.getStrideSize();
  35306. this._totalVertices = data.length / stride;
  35307. this.updateExtend(data, stride);
  35308. this._resetPointsArrayCache();
  35309. var meshes = this._meshes;
  35310. var numOfMeshes = meshes.length;
  35311. for (var index = 0; index < numOfMeshes; index++) {
  35312. var mesh = meshes[index];
  35313. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35314. mesh._createGlobalSubMesh(false);
  35315. mesh.computeWorldMatrix(true);
  35316. }
  35317. }
  35318. this.notifyUpdate(kind);
  35319. if (this._vertexArrayObjects) {
  35320. this._disposeVertexArrayObjects();
  35321. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35322. }
  35323. };
  35324. /**
  35325. * Update a specific vertex buffer
  35326. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35327. * It will do nothing if the buffer is not updatable
  35328. * @param kind defines the data kind (Position, normal, etc...)
  35329. * @param data defines the data to use
  35330. * @param offset defines the offset in the target buffer where to store the data
  35331. */
  35332. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35333. var vertexBuffer = this.getVertexBuffer(kind);
  35334. if (!vertexBuffer) {
  35335. return;
  35336. }
  35337. vertexBuffer.updateDirectly(data, offset);
  35338. this.notifyUpdate(kind);
  35339. };
  35340. /**
  35341. * Update a specific vertex buffer
  35342. * This function will create a new buffer if the current one is not updatable
  35343. * @param kind defines the data kind (Position, normal, etc...)
  35344. * @param data defines the data to use
  35345. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35346. */
  35347. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35348. if (updateExtends === void 0) { updateExtends = false; }
  35349. var vertexBuffer = this.getVertexBuffer(kind);
  35350. if (!vertexBuffer) {
  35351. return;
  35352. }
  35353. vertexBuffer.update(data);
  35354. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35355. var stride = vertexBuffer.getStrideSize();
  35356. this._totalVertices = data.length / stride;
  35357. this.updateBoundingInfo(updateExtends, data);
  35358. }
  35359. this.notifyUpdate(kind);
  35360. };
  35361. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35362. if (updateExtends) {
  35363. this.updateExtend(data);
  35364. }
  35365. var meshes = this._meshes;
  35366. var numOfMeshes = meshes.length;
  35367. this._resetPointsArrayCache();
  35368. for (var index = 0; index < numOfMeshes; index++) {
  35369. var mesh = meshes[index];
  35370. if (updateExtends) {
  35371. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35372. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35373. var subMesh = mesh.subMeshes[subIndex];
  35374. subMesh.refreshBoundingInfo();
  35375. }
  35376. }
  35377. }
  35378. };
  35379. /** @ignore */
  35380. Geometry.prototype._bind = function (effect, indexToBind) {
  35381. if (!effect) {
  35382. return;
  35383. }
  35384. if (indexToBind === undefined) {
  35385. indexToBind = this._indexBuffer;
  35386. }
  35387. var vbs = this.getVertexBuffers();
  35388. if (!vbs) {
  35389. return;
  35390. }
  35391. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35392. this._engine.bindBuffers(vbs, indexToBind, effect);
  35393. return;
  35394. }
  35395. // Using VAO
  35396. if (!this._vertexArrayObjects[effect.key]) {
  35397. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35398. }
  35399. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35400. };
  35401. /**
  35402. * Gets total number of vertices
  35403. * @returns the total number of vertices
  35404. */
  35405. Geometry.prototype.getTotalVertices = function () {
  35406. if (!this.isReady()) {
  35407. return 0;
  35408. }
  35409. return this._totalVertices;
  35410. };
  35411. /**
  35412. * Gets a specific vertex data attached to this geometry
  35413. * @param kind defines the data kind (Position, normal, etc...)
  35414. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35415. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35416. * @returns a float array containing vertex data
  35417. */
  35418. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35419. var vertexBuffer = this.getVertexBuffer(kind);
  35420. if (!vertexBuffer) {
  35421. return null;
  35422. }
  35423. var orig = vertexBuffer.getData();
  35424. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35425. return orig;
  35426. }
  35427. else {
  35428. var len = orig.length;
  35429. var copy = [];
  35430. for (var i = 0; i < len; i++) {
  35431. copy.push(orig[i]);
  35432. }
  35433. return copy;
  35434. }
  35435. };
  35436. /**
  35437. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35438. * @param kind defines the data kind (Position, normal, etc...)
  35439. * @returns true if the vertex buffer with the specified kind is updatable
  35440. */
  35441. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35442. var vb = this._vertexBuffers[kind];
  35443. if (!vb) {
  35444. return false;
  35445. }
  35446. return vb.isUpdatable();
  35447. };
  35448. /**
  35449. * Gets a specific vertex buffer
  35450. * @param kind defines the data kind (Position, normal, etc...)
  35451. * @returns a {BABYLON.VertexBuffer}
  35452. */
  35453. Geometry.prototype.getVertexBuffer = function (kind) {
  35454. if (!this.isReady()) {
  35455. return null;
  35456. }
  35457. return this._vertexBuffers[kind];
  35458. };
  35459. /**
  35460. * Returns all vertex buffers
  35461. * @return an object holding all vertex buffers indexed by kind
  35462. */
  35463. Geometry.prototype.getVertexBuffers = function () {
  35464. if (!this.isReady()) {
  35465. return null;
  35466. }
  35467. return this._vertexBuffers;
  35468. };
  35469. /**
  35470. * Gets a boolean indicating if specific vertex buffer is present
  35471. * @param kind defines the data kind (Position, normal, etc...)
  35472. * @returns true if data is present
  35473. */
  35474. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35475. if (!this._vertexBuffers) {
  35476. if (this._delayInfo) {
  35477. return this._delayInfo.indexOf(kind) !== -1;
  35478. }
  35479. return false;
  35480. }
  35481. return this._vertexBuffers[kind] !== undefined;
  35482. };
  35483. /**
  35484. * Gets a list of all attached data kinds (Position, normal, etc...)
  35485. * @returns a list of string containing all kinds
  35486. */
  35487. Geometry.prototype.getVerticesDataKinds = function () {
  35488. var result = [];
  35489. var kind;
  35490. if (!this._vertexBuffers && this._delayInfo) {
  35491. for (kind in this._delayInfo) {
  35492. result.push(kind);
  35493. }
  35494. }
  35495. else {
  35496. for (kind in this._vertexBuffers) {
  35497. result.push(kind);
  35498. }
  35499. }
  35500. return result;
  35501. };
  35502. /**
  35503. * Update index buffer
  35504. * @param indices defines the indices to store in the index buffer
  35505. * @param offset defines the offset in the target buffer where to store the data
  35506. */
  35507. Geometry.prototype.updateIndices = function (indices, offset) {
  35508. if (!this._indexBuffer) {
  35509. return;
  35510. }
  35511. if (!this._indexBufferIsUpdatable) {
  35512. this.setIndices(indices, null, true);
  35513. }
  35514. else {
  35515. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35516. }
  35517. };
  35518. /**
  35519. * Creates a new index buffer
  35520. * @param indices defines the indices to store in the index buffer
  35521. * @param totalVertices defines the total number of vertices (could be null)
  35522. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35523. */
  35524. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35525. if (totalVertices === void 0) { totalVertices = null; }
  35526. if (updatable === void 0) { updatable = false; }
  35527. if (this._indexBuffer) {
  35528. this._engine._releaseBuffer(this._indexBuffer);
  35529. }
  35530. this._disposeVertexArrayObjects();
  35531. this._indices = indices;
  35532. this._indexBufferIsUpdatable = updatable;
  35533. if (this._meshes.length !== 0 && this._indices) {
  35534. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35535. }
  35536. if (totalVertices != undefined) {
  35537. this._totalVertices = totalVertices;
  35538. }
  35539. var meshes = this._meshes;
  35540. var numOfMeshes = meshes.length;
  35541. for (var index = 0; index < numOfMeshes; index++) {
  35542. meshes[index]._createGlobalSubMesh(true);
  35543. }
  35544. this.notifyUpdate();
  35545. };
  35546. /**
  35547. * Return the total number of indices
  35548. * @returns the total number of indices
  35549. */
  35550. Geometry.prototype.getTotalIndices = function () {
  35551. if (!this.isReady()) {
  35552. return 0;
  35553. }
  35554. return this._indices.length;
  35555. };
  35556. /**
  35557. * Gets the index buffer array
  35558. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35559. * @returns the index buffer array
  35560. */
  35561. Geometry.prototype.getIndices = function (copyWhenShared) {
  35562. if (!this.isReady()) {
  35563. return null;
  35564. }
  35565. var orig = this._indices;
  35566. if (!copyWhenShared || this._meshes.length === 1) {
  35567. return orig;
  35568. }
  35569. else {
  35570. var len = orig.length;
  35571. var copy = [];
  35572. for (var i = 0; i < len; i++) {
  35573. copy.push(orig[i]);
  35574. }
  35575. return copy;
  35576. }
  35577. };
  35578. /**
  35579. * Gets the index buffer
  35580. * @return the index buffer
  35581. */
  35582. Geometry.prototype.getIndexBuffer = function () {
  35583. if (!this.isReady()) {
  35584. return null;
  35585. }
  35586. return this._indexBuffer;
  35587. };
  35588. /** @ignore */
  35589. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35590. if (effect === void 0) { effect = null; }
  35591. if (!effect || !this._vertexArrayObjects) {
  35592. return;
  35593. }
  35594. if (this._vertexArrayObjects[effect.key]) {
  35595. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35596. delete this._vertexArrayObjects[effect.key];
  35597. }
  35598. };
  35599. /**
  35600. * Release the associated resources for a specific mesh
  35601. * @param mesh defines the source mesh
  35602. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35603. */
  35604. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35605. var meshes = this._meshes;
  35606. var index = meshes.indexOf(mesh);
  35607. if (index === -1) {
  35608. return;
  35609. }
  35610. meshes.splice(index, 1);
  35611. mesh._geometry = null;
  35612. if (meshes.length === 0 && shouldDispose) {
  35613. this.dispose();
  35614. }
  35615. };
  35616. /**
  35617. * Apply current geometry to a given mesh
  35618. * @param mesh defines the mesh to apply geometry to
  35619. */
  35620. Geometry.prototype.applyToMesh = function (mesh) {
  35621. if (mesh._geometry === this) {
  35622. return;
  35623. }
  35624. var previousGeometry = mesh._geometry;
  35625. if (previousGeometry) {
  35626. previousGeometry.releaseForMesh(mesh);
  35627. }
  35628. var meshes = this._meshes;
  35629. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35630. mesh._geometry = this;
  35631. this._scene.pushGeometry(this);
  35632. meshes.push(mesh);
  35633. if (this.isReady()) {
  35634. this._applyToMesh(mesh);
  35635. }
  35636. else {
  35637. mesh._boundingInfo = this._boundingInfo;
  35638. }
  35639. };
  35640. Geometry.prototype.updateExtend = function (data, stride) {
  35641. if (data === void 0) { data = null; }
  35642. if (!data) {
  35643. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35644. }
  35645. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35646. };
  35647. Geometry.prototype._applyToMesh = function (mesh) {
  35648. var numOfMeshes = this._meshes.length;
  35649. // vertexBuffers
  35650. for (var kind in this._vertexBuffers) {
  35651. if (numOfMeshes === 1) {
  35652. this._vertexBuffers[kind].create();
  35653. }
  35654. var buffer = this._vertexBuffers[kind].getBuffer();
  35655. if (buffer)
  35656. buffer.references = numOfMeshes;
  35657. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35658. if (!this._extend) {
  35659. this.updateExtend(this._vertexBuffers[kind].getData());
  35660. }
  35661. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35662. mesh._createGlobalSubMesh(false);
  35663. //bounding info was just created again, world matrix should be applied again.
  35664. mesh._updateBoundingInfo();
  35665. }
  35666. }
  35667. // indexBuffer
  35668. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35669. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35670. }
  35671. if (this._indexBuffer) {
  35672. this._indexBuffer.references = numOfMeshes;
  35673. }
  35674. };
  35675. Geometry.prototype.notifyUpdate = function (kind) {
  35676. if (this.onGeometryUpdated) {
  35677. this.onGeometryUpdated(this, kind);
  35678. }
  35679. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35680. var mesh = _a[_i];
  35681. mesh._markSubMeshesAsAttributesDirty();
  35682. }
  35683. };
  35684. /**
  35685. * Load the geometry if it was flagged as delay loaded
  35686. * @param scene defines the hosting scene
  35687. * @param onLoaded defines a callback called when the geometry is loaded
  35688. */
  35689. Geometry.prototype.load = function (scene, onLoaded) {
  35690. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35691. return;
  35692. }
  35693. if (this.isReady()) {
  35694. if (onLoaded) {
  35695. onLoaded();
  35696. }
  35697. return;
  35698. }
  35699. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35700. this._queueLoad(scene, onLoaded);
  35701. };
  35702. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35703. var _this = this;
  35704. if (!this.delayLoadingFile) {
  35705. return;
  35706. }
  35707. scene._addPendingData(this);
  35708. scene._loadFile(this.delayLoadingFile, function (data) {
  35709. if (!_this._delayLoadingFunction) {
  35710. return;
  35711. }
  35712. _this._delayLoadingFunction(JSON.parse(data), _this);
  35713. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35714. _this._delayInfo = [];
  35715. scene._removePendingData(_this);
  35716. var meshes = _this._meshes;
  35717. var numOfMeshes = meshes.length;
  35718. for (var index = 0; index < numOfMeshes; index++) {
  35719. _this._applyToMesh(meshes[index]);
  35720. }
  35721. if (onLoaded) {
  35722. onLoaded();
  35723. }
  35724. }, undefined, true);
  35725. };
  35726. /**
  35727. * Invert the geometry to move from a right handed system to a left handed one.
  35728. */
  35729. Geometry.prototype.toLeftHanded = function () {
  35730. // Flip faces
  35731. var tIndices = this.getIndices(false);
  35732. if (tIndices != null && tIndices.length > 0) {
  35733. for (var i = 0; i < tIndices.length; i += 3) {
  35734. var tTemp = tIndices[i + 0];
  35735. tIndices[i + 0] = tIndices[i + 2];
  35736. tIndices[i + 2] = tTemp;
  35737. }
  35738. this.setIndices(tIndices);
  35739. }
  35740. // Negate position.z
  35741. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35742. if (tPositions != null && tPositions.length > 0) {
  35743. for (var i = 0; i < tPositions.length; i += 3) {
  35744. tPositions[i + 2] = -tPositions[i + 2];
  35745. }
  35746. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35747. }
  35748. // Negate normal.z
  35749. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35750. if (tNormals != null && tNormals.length > 0) {
  35751. for (var i = 0; i < tNormals.length; i += 3) {
  35752. tNormals[i + 2] = -tNormals[i + 2];
  35753. }
  35754. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35755. }
  35756. };
  35757. // Cache
  35758. /** @ignore */
  35759. Geometry.prototype._resetPointsArrayCache = function () {
  35760. this._positions = null;
  35761. };
  35762. /** @ignore */
  35763. Geometry.prototype._generatePointsArray = function () {
  35764. if (this._positions)
  35765. return true;
  35766. this._positions = [];
  35767. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35768. if (!data) {
  35769. return false;
  35770. }
  35771. for (var index = 0; index < data.length; index += 3) {
  35772. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35773. }
  35774. return true;
  35775. };
  35776. /**
  35777. * Gets a value indicating if the geometry is disposed
  35778. * @returns true if the geometry was disposed
  35779. */
  35780. Geometry.prototype.isDisposed = function () {
  35781. return this._isDisposed;
  35782. };
  35783. Geometry.prototype._disposeVertexArrayObjects = function () {
  35784. if (this._vertexArrayObjects) {
  35785. for (var kind in this._vertexArrayObjects) {
  35786. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35787. }
  35788. this._vertexArrayObjects = {};
  35789. }
  35790. };
  35791. /**
  35792. * Free all associated resources
  35793. */
  35794. Geometry.prototype.dispose = function () {
  35795. var meshes = this._meshes;
  35796. var numOfMeshes = meshes.length;
  35797. var index;
  35798. for (index = 0; index < numOfMeshes; index++) {
  35799. this.releaseForMesh(meshes[index]);
  35800. }
  35801. this._meshes = [];
  35802. this._disposeVertexArrayObjects();
  35803. for (var kind in this._vertexBuffers) {
  35804. this._vertexBuffers[kind].dispose();
  35805. }
  35806. this._vertexBuffers = {};
  35807. this._totalVertices = 0;
  35808. if (this._indexBuffer) {
  35809. this._engine._releaseBuffer(this._indexBuffer);
  35810. }
  35811. this._indexBuffer = null;
  35812. this._indices = [];
  35813. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35814. this.delayLoadingFile = null;
  35815. this._delayLoadingFunction = null;
  35816. this._delayInfo = [];
  35817. this._boundingInfo = null;
  35818. this._scene.removeGeometry(this);
  35819. this._isDisposed = true;
  35820. };
  35821. /**
  35822. * Clone the current geometry into a new geometry
  35823. * @param id defines the unique ID of the new geometry
  35824. * @returns a new geometry object
  35825. */
  35826. Geometry.prototype.copy = function (id) {
  35827. var vertexData = new BABYLON.VertexData();
  35828. vertexData.indices = [];
  35829. var indices = this.getIndices();
  35830. if (indices) {
  35831. for (var index = 0; index < indices.length; index++) {
  35832. vertexData.indices.push(indices[index]);
  35833. }
  35834. }
  35835. var updatable = false;
  35836. var stopChecking = false;
  35837. var kind;
  35838. for (kind in this._vertexBuffers) {
  35839. // using slice() to make a copy of the array and not just reference it
  35840. var data = this.getVerticesData(kind);
  35841. if (data instanceof Float32Array) {
  35842. vertexData.set(new Float32Array(data), kind);
  35843. }
  35844. else {
  35845. vertexData.set(data.slice(0), kind);
  35846. }
  35847. if (!stopChecking) {
  35848. var vb = this.getVertexBuffer(kind);
  35849. if (vb) {
  35850. updatable = vb.isUpdatable();
  35851. stopChecking = !updatable;
  35852. }
  35853. }
  35854. }
  35855. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35856. geometry.delayLoadState = this.delayLoadState;
  35857. geometry.delayLoadingFile = this.delayLoadingFile;
  35858. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35859. for (kind in this._delayInfo) {
  35860. geometry._delayInfo = geometry._delayInfo || [];
  35861. geometry._delayInfo.push(kind);
  35862. }
  35863. // Bounding info
  35864. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35865. return geometry;
  35866. };
  35867. /**
  35868. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35869. * @return a JSON representation of the current geometry data (without the vertices data)
  35870. */
  35871. Geometry.prototype.serialize = function () {
  35872. var serializationObject = {};
  35873. serializationObject.id = this.id;
  35874. serializationObject.updatable = this._updatable;
  35875. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35876. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35877. }
  35878. return serializationObject;
  35879. };
  35880. Geometry.prototype.toNumberArray = function (origin) {
  35881. if (Array.isArray(origin)) {
  35882. return origin;
  35883. }
  35884. else {
  35885. return Array.prototype.slice.call(origin);
  35886. }
  35887. };
  35888. /**
  35889. * Serialize all vertices data into a JSON oject
  35890. * @returns a JSON representation of the current geometry data
  35891. */
  35892. Geometry.prototype.serializeVerticeData = function () {
  35893. var serializationObject = this.serialize();
  35894. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35895. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35896. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35897. serializationObject.positions._updatable = true;
  35898. }
  35899. }
  35900. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35901. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35902. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35903. serializationObject.normals._updatable = true;
  35904. }
  35905. }
  35906. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35907. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35908. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35909. serializationObject.tangets._updatable = true;
  35910. }
  35911. }
  35912. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35913. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35914. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35915. serializationObject.uvs._updatable = true;
  35916. }
  35917. }
  35918. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35919. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35920. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35921. serializationObject.uv2s._updatable = true;
  35922. }
  35923. }
  35924. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35925. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35926. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35927. serializationObject.uv3s._updatable = true;
  35928. }
  35929. }
  35930. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35931. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35932. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35933. serializationObject.uv4s._updatable = true;
  35934. }
  35935. }
  35936. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35937. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35938. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35939. serializationObject.uv5s._updatable = true;
  35940. }
  35941. }
  35942. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35943. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35944. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35945. serializationObject.uv6s._updatable = true;
  35946. }
  35947. }
  35948. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35949. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35950. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35951. serializationObject.colors._updatable = true;
  35952. }
  35953. }
  35954. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35955. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35956. serializationObject.matricesIndices._isExpanded = true;
  35957. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35958. serializationObject.matricesIndices._updatable = true;
  35959. }
  35960. }
  35961. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35962. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35963. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35964. serializationObject.matricesWeights._updatable = true;
  35965. }
  35966. }
  35967. serializationObject.indices = this.toNumberArray(this.getIndices());
  35968. return serializationObject;
  35969. };
  35970. // Statics
  35971. /**
  35972. * Extracts a clone of a mesh geometry
  35973. * @param mesh defines the source mesh
  35974. * @param id defines the unique ID of the new geometry object
  35975. * @returns the new geometry object
  35976. */
  35977. Geometry.ExtractFromMesh = function (mesh, id) {
  35978. var geometry = mesh._geometry;
  35979. if (!geometry) {
  35980. return null;
  35981. }
  35982. return geometry.copy(id);
  35983. };
  35984. /**
  35985. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35986. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35987. * Be aware Math.random() could cause collisions, but:
  35988. * "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"
  35989. * @returns a string containing a new GUID
  35990. */
  35991. Geometry.RandomId = function () {
  35992. return BABYLON.Tools.RandomId();
  35993. };
  35994. /** @ignore */
  35995. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35996. var scene = mesh.getScene();
  35997. // Geometry
  35998. var geometryId = parsedGeometry.geometryId;
  35999. if (geometryId) {
  36000. var geometry = scene.getGeometryByID(geometryId);
  36001. if (geometry) {
  36002. geometry.applyToMesh(mesh);
  36003. }
  36004. }
  36005. else if (parsedGeometry instanceof ArrayBuffer) {
  36006. var binaryInfo = mesh._binaryInfo;
  36007. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36008. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36009. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36010. }
  36011. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36012. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36013. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36014. }
  36015. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36016. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36017. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36018. }
  36019. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36020. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36021. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36022. }
  36023. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36024. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36025. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36026. }
  36027. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36028. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36029. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36030. }
  36031. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36032. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36033. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36034. }
  36035. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36036. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36037. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36038. }
  36039. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36040. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36041. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36042. }
  36043. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36044. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36045. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36046. }
  36047. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36048. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36049. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36050. }
  36051. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36052. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36053. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36054. }
  36055. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36056. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36057. mesh.setIndices(indicesData, null);
  36058. }
  36059. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36060. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36061. mesh.subMeshes = [];
  36062. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36063. var materialIndex = subMeshesData[(i * 5) + 0];
  36064. var verticesStart = subMeshesData[(i * 5) + 1];
  36065. var verticesCount = subMeshesData[(i * 5) + 2];
  36066. var indexStart = subMeshesData[(i * 5) + 3];
  36067. var indexCount = subMeshesData[(i * 5) + 4];
  36068. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36069. }
  36070. }
  36071. }
  36072. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36073. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36074. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36075. if (parsedGeometry.tangents) {
  36076. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36077. }
  36078. if (parsedGeometry.uvs) {
  36079. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36080. }
  36081. if (parsedGeometry.uvs2) {
  36082. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36083. }
  36084. if (parsedGeometry.uvs3) {
  36085. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36086. }
  36087. if (parsedGeometry.uvs4) {
  36088. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36089. }
  36090. if (parsedGeometry.uvs5) {
  36091. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36092. }
  36093. if (parsedGeometry.uvs6) {
  36094. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36095. }
  36096. if (parsedGeometry.colors) {
  36097. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36098. }
  36099. if (parsedGeometry.matricesIndices) {
  36100. if (!parsedGeometry.matricesIndices._isExpanded) {
  36101. var floatIndices = [];
  36102. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36103. var matricesIndex = parsedGeometry.matricesIndices[i];
  36104. floatIndices.push(matricesIndex & 0x000000FF);
  36105. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36106. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36107. floatIndices.push(matricesIndex >> 24);
  36108. }
  36109. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36110. }
  36111. else {
  36112. delete parsedGeometry.matricesIndices._isExpanded;
  36113. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36114. }
  36115. }
  36116. if (parsedGeometry.matricesIndicesExtra) {
  36117. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36118. var floatIndices = [];
  36119. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36120. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36121. floatIndices.push(matricesIndex & 0x000000FF);
  36122. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36123. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36124. floatIndices.push(matricesIndex >> 24);
  36125. }
  36126. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36127. }
  36128. else {
  36129. delete parsedGeometry.matricesIndices._isExpanded;
  36130. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36131. }
  36132. }
  36133. if (parsedGeometry.matricesWeights) {
  36134. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36135. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36136. }
  36137. if (parsedGeometry.matricesWeightsExtra) {
  36138. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36139. }
  36140. mesh.setIndices(parsedGeometry.indices, null);
  36141. }
  36142. // SubMeshes
  36143. if (parsedGeometry.subMeshes) {
  36144. mesh.subMeshes = [];
  36145. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36146. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36147. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36148. }
  36149. }
  36150. // Flat shading
  36151. if (mesh._shouldGenerateFlatShading) {
  36152. mesh.convertToFlatShadedMesh();
  36153. delete mesh._shouldGenerateFlatShading;
  36154. }
  36155. // Update
  36156. mesh.computeWorldMatrix(true);
  36157. // Octree
  36158. var sceneOctree = scene.selectionOctree;
  36159. if (sceneOctree !== undefined && sceneOctree !== null) {
  36160. sceneOctree.addMesh(mesh);
  36161. }
  36162. };
  36163. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36164. var epsilon = 1e-3;
  36165. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36166. return;
  36167. }
  36168. var noInfluenceBoneIndex = 0.0;
  36169. if (parsedGeometry.skeletonId > -1) {
  36170. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36171. if (!skeleton) {
  36172. return;
  36173. }
  36174. noInfluenceBoneIndex = skeleton.bones.length;
  36175. }
  36176. else {
  36177. return;
  36178. }
  36179. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36180. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36181. var matricesWeights = parsedGeometry.matricesWeights;
  36182. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36183. var influencers = parsedGeometry.numBoneInfluencer;
  36184. var size = matricesWeights.length;
  36185. for (var i = 0; i < size; i += 4) {
  36186. var weight = 0.0;
  36187. var firstZeroWeight = -1;
  36188. for (var j = 0; j < 4; j++) {
  36189. var w = matricesWeights[i + j];
  36190. weight += w;
  36191. if (w < epsilon && firstZeroWeight < 0) {
  36192. firstZeroWeight = j;
  36193. }
  36194. }
  36195. if (matricesWeightsExtra) {
  36196. for (var j = 0; j < 4; j++) {
  36197. var w = matricesWeightsExtra[i + j];
  36198. weight += w;
  36199. if (w < epsilon && firstZeroWeight < 0) {
  36200. firstZeroWeight = j + 4;
  36201. }
  36202. }
  36203. }
  36204. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36205. firstZeroWeight = influencers - 1;
  36206. }
  36207. if (weight > epsilon) {
  36208. var mweight = 1.0 / weight;
  36209. for (var j = 0; j < 4; j++) {
  36210. matricesWeights[i + j] *= mweight;
  36211. }
  36212. if (matricesWeightsExtra) {
  36213. for (var j = 0; j < 4; j++) {
  36214. matricesWeightsExtra[i + j] *= mweight;
  36215. }
  36216. }
  36217. }
  36218. else {
  36219. if (firstZeroWeight >= 4) {
  36220. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36221. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36222. }
  36223. else {
  36224. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36225. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36226. }
  36227. }
  36228. }
  36229. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36230. if (parsedGeometry.matricesWeightsExtra) {
  36231. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36232. }
  36233. };
  36234. /**
  36235. * Create a new geometry from persisted data (Using .babylon file format)
  36236. * @param parsedVertexData defines the persisted data
  36237. * @param scene defines the hosting scene
  36238. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36239. * @returns the new geometry object
  36240. */
  36241. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36242. if (scene.getGeometryByID(parsedVertexData.id)) {
  36243. return null; // null since geometry could be something else than a box...
  36244. }
  36245. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36246. if (BABYLON.Tags) {
  36247. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36248. }
  36249. if (parsedVertexData.delayLoadingFile) {
  36250. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36251. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36252. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36253. geometry._delayInfo = [];
  36254. if (parsedVertexData.hasUVs) {
  36255. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36256. }
  36257. if (parsedVertexData.hasUVs2) {
  36258. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36259. }
  36260. if (parsedVertexData.hasUVs3) {
  36261. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36262. }
  36263. if (parsedVertexData.hasUVs4) {
  36264. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36265. }
  36266. if (parsedVertexData.hasUVs5) {
  36267. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36268. }
  36269. if (parsedVertexData.hasUVs6) {
  36270. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36271. }
  36272. if (parsedVertexData.hasColors) {
  36273. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36274. }
  36275. if (parsedVertexData.hasMatricesIndices) {
  36276. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36277. }
  36278. if (parsedVertexData.hasMatricesWeights) {
  36279. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36280. }
  36281. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36282. }
  36283. else {
  36284. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36285. }
  36286. scene.pushGeometry(geometry, true);
  36287. return geometry;
  36288. };
  36289. return Geometry;
  36290. }());
  36291. BABYLON.Geometry = Geometry;
  36292. // Primitives
  36293. /// Abstract class
  36294. /**
  36295. * Abstract class used to provide common services for all typed geometries
  36296. */
  36297. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36298. __extends(_PrimitiveGeometry, _super);
  36299. /**
  36300. * Creates a new typed geometry
  36301. * @param id defines the unique ID of the geometry
  36302. * @param scene defines the hosting scene
  36303. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36304. * @param mesh defines the hosting mesh (can be null)
  36305. */
  36306. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36307. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36308. if (mesh === void 0) { mesh = null; }
  36309. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36310. _this._canBeRegenerated = _canBeRegenerated;
  36311. _this._beingRegenerated = true;
  36312. _this.regenerate();
  36313. _this._beingRegenerated = false;
  36314. return _this;
  36315. }
  36316. /**
  36317. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36318. * @returns true if the geometry can be regenerated
  36319. */
  36320. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36321. return this._canBeRegenerated;
  36322. };
  36323. /**
  36324. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36325. */
  36326. _PrimitiveGeometry.prototype.regenerate = function () {
  36327. if (!this._canBeRegenerated) {
  36328. return;
  36329. }
  36330. this._beingRegenerated = true;
  36331. this.setAllVerticesData(this._regenerateVertexData(), false);
  36332. this._beingRegenerated = false;
  36333. };
  36334. /**
  36335. * Clone the geometry
  36336. * @param id defines the unique ID of the new geometry
  36337. * @returns the new geometry
  36338. */
  36339. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36340. return _super.prototype.copy.call(this, id);
  36341. };
  36342. // overrides
  36343. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36344. if (!this._beingRegenerated) {
  36345. return;
  36346. }
  36347. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36348. };
  36349. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36350. if (!this._beingRegenerated) {
  36351. return;
  36352. }
  36353. _super.prototype.setVerticesData.call(this, kind, data, false);
  36354. };
  36355. // to override
  36356. /** @ignore */
  36357. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36358. throw new Error("Abstract method");
  36359. };
  36360. _PrimitiveGeometry.prototype.copy = function (id) {
  36361. throw new Error("Must be overriden in sub-classes.");
  36362. };
  36363. _PrimitiveGeometry.prototype.serialize = function () {
  36364. var serializationObject = _super.prototype.serialize.call(this);
  36365. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36366. return serializationObject;
  36367. };
  36368. return _PrimitiveGeometry;
  36369. }(Geometry));
  36370. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36371. /**
  36372. * Creates a ribbon geometry
  36373. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36374. */
  36375. var RibbonGeometry = /** @class */ (function (_super) {
  36376. __extends(RibbonGeometry, _super);
  36377. /**
  36378. * Creates a ribbon geometry
  36379. * @param id defines the unique ID of the geometry
  36380. * @param scene defines the hosting scene
  36381. * @param pathArray defines the array of paths to use
  36382. * @param closeArray defines if the last path and the first path must be joined
  36383. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36384. * @param offset defines the offset between points
  36385. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36386. * @param mesh defines the hosting mesh (can be null)
  36387. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36388. */
  36389. function RibbonGeometry(id, scene,
  36390. /**
  36391. * Defines the array of paths to use
  36392. */
  36393. pathArray,
  36394. /**
  36395. * Defines if the last and first points of each path in your pathArray must be joined
  36396. */
  36397. closeArray,
  36398. /**
  36399. * Defines if the last and first points of each path in your pathArray must be joined
  36400. */
  36401. closePath,
  36402. /**
  36403. * Defines the offset between points
  36404. */
  36405. offset, canBeRegenerated, mesh,
  36406. /**
  36407. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36408. */
  36409. side) {
  36410. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36411. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36412. _this.pathArray = pathArray;
  36413. _this.closeArray = closeArray;
  36414. _this.closePath = closePath;
  36415. _this.offset = offset;
  36416. _this.side = side;
  36417. return _this;
  36418. }
  36419. /** @ignore */
  36420. RibbonGeometry.prototype._regenerateVertexData = function () {
  36421. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36422. };
  36423. RibbonGeometry.prototype.copy = function (id) {
  36424. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36425. };
  36426. return RibbonGeometry;
  36427. }(_PrimitiveGeometry));
  36428. BABYLON.RibbonGeometry = RibbonGeometry;
  36429. /**
  36430. * Creates a box geometry
  36431. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36432. */
  36433. var BoxGeometry = /** @class */ (function (_super) {
  36434. __extends(BoxGeometry, _super);
  36435. /**
  36436. * Creates a box geometry
  36437. * @param id defines the unique ID of the geometry
  36438. * @param scene defines the hosting scene
  36439. * @param size defines the zise of the box (width, height and depth are the same)
  36440. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36441. * @param mesh defines the hosting mesh (can be null)
  36442. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36443. */
  36444. function BoxGeometry(id, scene,
  36445. /**
  36446. * Defines the zise of the box (width, height and depth are the same)
  36447. */
  36448. size, canBeRegenerated, mesh,
  36449. /**
  36450. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36451. */
  36452. side) {
  36453. if (mesh === void 0) { mesh = null; }
  36454. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36455. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36456. _this.size = size;
  36457. _this.side = side;
  36458. return _this;
  36459. }
  36460. BoxGeometry.prototype._regenerateVertexData = function () {
  36461. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36462. };
  36463. BoxGeometry.prototype.copy = function (id) {
  36464. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36465. };
  36466. BoxGeometry.prototype.serialize = function () {
  36467. var serializationObject = _super.prototype.serialize.call(this);
  36468. serializationObject.size = this.size;
  36469. return serializationObject;
  36470. };
  36471. BoxGeometry.Parse = function (parsedBox, scene) {
  36472. if (scene.getGeometryByID(parsedBox.id)) {
  36473. return null; // null since geometry could be something else than a box...
  36474. }
  36475. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36476. if (BABYLON.Tags) {
  36477. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36478. }
  36479. scene.pushGeometry(box, true);
  36480. return box;
  36481. };
  36482. return BoxGeometry;
  36483. }(_PrimitiveGeometry));
  36484. BABYLON.BoxGeometry = BoxGeometry;
  36485. /**
  36486. * Creates a sphere geometry
  36487. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36488. */
  36489. var SphereGeometry = /** @class */ (function (_super) {
  36490. __extends(SphereGeometry, _super);
  36491. /**
  36492. * Create a new sphere geometry
  36493. * @param id defines the unique ID of the geometry
  36494. * @param scene defines the hosting scene
  36495. * @param segments defines the number of segments to use to create the sphere
  36496. * @param diameter defines the diameter of the sphere
  36497. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36498. * @param mesh defines the hosting mesh (can be null)
  36499. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36500. */
  36501. function SphereGeometry(id, scene,
  36502. /**
  36503. * Defines the number of segments to use to create the sphere
  36504. */
  36505. segments,
  36506. /**
  36507. * Defines the diameter of the sphere
  36508. */
  36509. diameter, canBeRegenerated, mesh,
  36510. /**
  36511. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36512. */
  36513. side) {
  36514. if (mesh === void 0) { mesh = null; }
  36515. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36516. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36517. _this.segments = segments;
  36518. _this.diameter = diameter;
  36519. _this.side = side;
  36520. return _this;
  36521. }
  36522. SphereGeometry.prototype._regenerateVertexData = function () {
  36523. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36524. };
  36525. SphereGeometry.prototype.copy = function (id) {
  36526. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36527. };
  36528. SphereGeometry.prototype.serialize = function () {
  36529. var serializationObject = _super.prototype.serialize.call(this);
  36530. serializationObject.segments = this.segments;
  36531. serializationObject.diameter = this.diameter;
  36532. return serializationObject;
  36533. };
  36534. SphereGeometry.Parse = function (parsedSphere, scene) {
  36535. if (scene.getGeometryByID(parsedSphere.id)) {
  36536. return null; // null since geometry could be something else than a sphere...
  36537. }
  36538. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36539. if (BABYLON.Tags) {
  36540. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36541. }
  36542. scene.pushGeometry(sphere, true);
  36543. return sphere;
  36544. };
  36545. return SphereGeometry;
  36546. }(_PrimitiveGeometry));
  36547. BABYLON.SphereGeometry = SphereGeometry;
  36548. /**
  36549. * Creates a disc geometry
  36550. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36551. */
  36552. var DiscGeometry = /** @class */ (function (_super) {
  36553. __extends(DiscGeometry, _super);
  36554. /**
  36555. * Creates a new disc geometry
  36556. * @param id defines the unique ID of the geometry
  36557. * @param scene defines the hosting scene
  36558. * @param radius defines the radius of the disc
  36559. * @param tessellation defines the tesselation factor to apply to the disc
  36560. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36561. * @param mesh defines the hosting mesh (can be null)
  36562. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36563. */
  36564. function DiscGeometry(id, scene,
  36565. /**
  36566. * Defines the radius of the disc
  36567. */
  36568. radius,
  36569. /**
  36570. * Defines the tesselation factor to apply to the disc
  36571. */
  36572. tessellation, canBeRegenerated, mesh,
  36573. /**
  36574. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36575. */
  36576. side) {
  36577. if (mesh === void 0) { mesh = null; }
  36578. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36579. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36580. _this.radius = radius;
  36581. _this.tessellation = tessellation;
  36582. _this.side = side;
  36583. return _this;
  36584. }
  36585. DiscGeometry.prototype._regenerateVertexData = function () {
  36586. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36587. };
  36588. DiscGeometry.prototype.copy = function (id) {
  36589. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36590. };
  36591. return DiscGeometry;
  36592. }(_PrimitiveGeometry));
  36593. BABYLON.DiscGeometry = DiscGeometry;
  36594. /**
  36595. * Creates a new cylinder geometry
  36596. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36597. */
  36598. var CylinderGeometry = /** @class */ (function (_super) {
  36599. __extends(CylinderGeometry, _super);
  36600. /**
  36601. * Creates a new cylinder geometry
  36602. * @param id defines the unique ID of the geometry
  36603. * @param scene defines the hosting scene
  36604. * @param height defines the height of the cylinder
  36605. * @param diameterTop defines the diameter of the cylinder's top cap
  36606. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36607. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36608. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36609. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36610. * @param mesh defines the hosting mesh (can be null)
  36611. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36612. */
  36613. function CylinderGeometry(id, scene,
  36614. /**
  36615. * Defines the height of the cylinder
  36616. */
  36617. height,
  36618. /**
  36619. * Defines the diameter of the cylinder's top cap
  36620. */
  36621. diameterTop,
  36622. /**
  36623. * Defines the diameter of the cylinder's bottom cap
  36624. */
  36625. diameterBottom,
  36626. /**
  36627. * Defines the tessellation factor to apply to the cylinder
  36628. */
  36629. tessellation,
  36630. /**
  36631. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36632. */
  36633. subdivisions, canBeRegenerated, mesh,
  36634. /**
  36635. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36636. */
  36637. side) {
  36638. if (subdivisions === void 0) { subdivisions = 1; }
  36639. if (mesh === void 0) { mesh = null; }
  36640. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36641. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36642. _this.height = height;
  36643. _this.diameterTop = diameterTop;
  36644. _this.diameterBottom = diameterBottom;
  36645. _this.tessellation = tessellation;
  36646. _this.subdivisions = subdivisions;
  36647. _this.side = side;
  36648. return _this;
  36649. }
  36650. CylinderGeometry.prototype._regenerateVertexData = function () {
  36651. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36652. };
  36653. CylinderGeometry.prototype.copy = function (id) {
  36654. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36655. };
  36656. CylinderGeometry.prototype.serialize = function () {
  36657. var serializationObject = _super.prototype.serialize.call(this);
  36658. serializationObject.height = this.height;
  36659. serializationObject.diameterTop = this.diameterTop;
  36660. serializationObject.diameterBottom = this.diameterBottom;
  36661. serializationObject.tessellation = this.tessellation;
  36662. return serializationObject;
  36663. };
  36664. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36665. if (scene.getGeometryByID(parsedCylinder.id)) {
  36666. return null; // null since geometry could be something else than a cylinder...
  36667. }
  36668. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36669. if (BABYLON.Tags) {
  36670. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36671. }
  36672. scene.pushGeometry(cylinder, true);
  36673. return cylinder;
  36674. };
  36675. return CylinderGeometry;
  36676. }(_PrimitiveGeometry));
  36677. BABYLON.CylinderGeometry = CylinderGeometry;
  36678. /**
  36679. * Creates a new torus geometry
  36680. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36681. */
  36682. var TorusGeometry = /** @class */ (function (_super) {
  36683. __extends(TorusGeometry, _super);
  36684. /**
  36685. * Creates a new torus geometry
  36686. * @param id defines the unique ID of the geometry
  36687. * @param scene defines the hosting scene
  36688. * @param diameter defines the diameter of the torus
  36689. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36690. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36691. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36692. * @param mesh defines the hosting mesh (can be null)
  36693. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36694. */
  36695. function TorusGeometry(id, scene,
  36696. /**
  36697. * Defines the diameter of the torus
  36698. */
  36699. diameter,
  36700. /**
  36701. * Defines the thickness of the torus (ie. internal diameter)
  36702. */
  36703. thickness,
  36704. /**
  36705. * Defines the tesselation factor to apply to the torus
  36706. */
  36707. tessellation, canBeRegenerated, mesh,
  36708. /**
  36709. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36710. */
  36711. side) {
  36712. if (mesh === void 0) { mesh = null; }
  36713. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36714. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36715. _this.diameter = diameter;
  36716. _this.thickness = thickness;
  36717. _this.tessellation = tessellation;
  36718. _this.side = side;
  36719. return _this;
  36720. }
  36721. TorusGeometry.prototype._regenerateVertexData = function () {
  36722. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36723. };
  36724. TorusGeometry.prototype.copy = function (id) {
  36725. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36726. };
  36727. TorusGeometry.prototype.serialize = function () {
  36728. var serializationObject = _super.prototype.serialize.call(this);
  36729. serializationObject.diameter = this.diameter;
  36730. serializationObject.thickness = this.thickness;
  36731. serializationObject.tessellation = this.tessellation;
  36732. return serializationObject;
  36733. };
  36734. TorusGeometry.Parse = function (parsedTorus, scene) {
  36735. if (scene.getGeometryByID(parsedTorus.id)) {
  36736. return null; // null since geometry could be something else than a torus...
  36737. }
  36738. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36739. if (BABYLON.Tags) {
  36740. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36741. }
  36742. scene.pushGeometry(torus, true);
  36743. return torus;
  36744. };
  36745. return TorusGeometry;
  36746. }(_PrimitiveGeometry));
  36747. BABYLON.TorusGeometry = TorusGeometry;
  36748. /**
  36749. * Creates a new ground geometry
  36750. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36751. */
  36752. var GroundGeometry = /** @class */ (function (_super) {
  36753. __extends(GroundGeometry, _super);
  36754. /**
  36755. * Creates a new ground geometry
  36756. * @param id defines the unique ID of the geometry
  36757. * @param scene defines the hosting scene
  36758. * @param width defines the width of the ground
  36759. * @param height defines the height of the ground
  36760. * @param subdivisions defines the subdivisions to apply to the ground
  36761. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36762. * @param mesh defines the hosting mesh (can be null)
  36763. */
  36764. function GroundGeometry(id, scene,
  36765. /**
  36766. * Defines the width of the ground
  36767. */
  36768. width,
  36769. /**
  36770. * Defines the height of the ground
  36771. */
  36772. height,
  36773. /**
  36774. * Defines the subdivisions to apply to the ground
  36775. */
  36776. subdivisions, canBeRegenerated, mesh) {
  36777. if (mesh === void 0) { mesh = null; }
  36778. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36779. _this.width = width;
  36780. _this.height = height;
  36781. _this.subdivisions = subdivisions;
  36782. return _this;
  36783. }
  36784. GroundGeometry.prototype._regenerateVertexData = function () {
  36785. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36786. };
  36787. GroundGeometry.prototype.copy = function (id) {
  36788. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36789. };
  36790. GroundGeometry.prototype.serialize = function () {
  36791. var serializationObject = _super.prototype.serialize.call(this);
  36792. serializationObject.width = this.width;
  36793. serializationObject.height = this.height;
  36794. serializationObject.subdivisions = this.subdivisions;
  36795. return serializationObject;
  36796. };
  36797. GroundGeometry.Parse = function (parsedGround, scene) {
  36798. if (scene.getGeometryByID(parsedGround.id)) {
  36799. return null; // null since geometry could be something else than a ground...
  36800. }
  36801. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36802. if (BABYLON.Tags) {
  36803. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36804. }
  36805. scene.pushGeometry(ground, true);
  36806. return ground;
  36807. };
  36808. return GroundGeometry;
  36809. }(_PrimitiveGeometry));
  36810. BABYLON.GroundGeometry = GroundGeometry;
  36811. /**
  36812. * Creates a tiled ground geometry
  36813. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36814. */
  36815. var TiledGroundGeometry = /** @class */ (function (_super) {
  36816. __extends(TiledGroundGeometry, _super);
  36817. /**
  36818. * Creates a tiled ground geometry
  36819. * @param id defines the unique ID of the geometry
  36820. * @param scene defines the hosting scene
  36821. * @param xmin defines the minimum value on X axis
  36822. * @param zmin defines the minimum value on Z axis
  36823. * @param xmax defines the maximum value on X axis
  36824. * @param zmax defines the maximum value on Z axis
  36825. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36826. * @param precision defines the precision to use when computing the tiles
  36827. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36828. * @param mesh defines the hosting mesh (can be null)
  36829. */
  36830. function TiledGroundGeometry(id, scene,
  36831. /**
  36832. * Defines the minimum value on X axis
  36833. */
  36834. xmin,
  36835. /**
  36836. * Defines the minimum value on Z axis
  36837. */
  36838. zmin,
  36839. /**
  36840. * Defines the maximum value on X axis
  36841. */
  36842. xmax,
  36843. /**
  36844. * Defines the maximum value on Z axis
  36845. */
  36846. zmax,
  36847. /**
  36848. * Defines the subdivisions to apply to the ground
  36849. */
  36850. subdivisions,
  36851. /**
  36852. * Defines the precision to use when computing the tiles
  36853. */
  36854. precision, canBeRegenerated, mesh) {
  36855. if (mesh === void 0) { mesh = null; }
  36856. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36857. _this.xmin = xmin;
  36858. _this.zmin = zmin;
  36859. _this.xmax = xmax;
  36860. _this.zmax = zmax;
  36861. _this.subdivisions = subdivisions;
  36862. _this.precision = precision;
  36863. return _this;
  36864. }
  36865. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36866. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36867. };
  36868. TiledGroundGeometry.prototype.copy = function (id) {
  36869. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36870. };
  36871. return TiledGroundGeometry;
  36872. }(_PrimitiveGeometry));
  36873. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36874. /**
  36875. * Creates a plane geometry
  36876. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36877. */
  36878. var PlaneGeometry = /** @class */ (function (_super) {
  36879. __extends(PlaneGeometry, _super);
  36880. /**
  36881. * Creates a plane geometry
  36882. * @param id defines the unique ID of the geometry
  36883. * @param scene defines the hosting scene
  36884. * @param size defines the size of the plane (width === height)
  36885. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36886. * @param mesh defines the hosting mesh (can be null)
  36887. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36888. */
  36889. function PlaneGeometry(id, scene,
  36890. /**
  36891. * Defines the size of the plane (width === height)
  36892. */
  36893. size, canBeRegenerated, mesh,
  36894. /**
  36895. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36896. */
  36897. side) {
  36898. if (mesh === void 0) { mesh = null; }
  36899. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36900. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36901. _this.size = size;
  36902. _this.side = side;
  36903. return _this;
  36904. }
  36905. PlaneGeometry.prototype._regenerateVertexData = function () {
  36906. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36907. };
  36908. PlaneGeometry.prototype.copy = function (id) {
  36909. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36910. };
  36911. PlaneGeometry.prototype.serialize = function () {
  36912. var serializationObject = _super.prototype.serialize.call(this);
  36913. serializationObject.size = this.size;
  36914. return serializationObject;
  36915. };
  36916. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36917. if (scene.getGeometryByID(parsedPlane.id)) {
  36918. return null; // null since geometry could be something else than a ground...
  36919. }
  36920. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36921. if (BABYLON.Tags) {
  36922. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36923. }
  36924. scene.pushGeometry(plane, true);
  36925. return plane;
  36926. };
  36927. return PlaneGeometry;
  36928. }(_PrimitiveGeometry));
  36929. BABYLON.PlaneGeometry = PlaneGeometry;
  36930. /**
  36931. * Creates a torus knot geometry
  36932. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36933. */
  36934. var TorusKnotGeometry = /** @class */ (function (_super) {
  36935. __extends(TorusKnotGeometry, _super);
  36936. /**
  36937. * Creates a torus knot geometry
  36938. * @param id defines the unique ID of the geometry
  36939. * @param scene defines the hosting scene
  36940. * @param radius defines the radius of the torus knot
  36941. * @param tube defines the thickness of the torus knot tube
  36942. * @param radialSegments defines the number of radial segments
  36943. * @param tubularSegments defines the number of tubular segments
  36944. * @param p defines the first number of windings
  36945. * @param q defines the second number of windings
  36946. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36947. * @param mesh defines the hosting mesh (can be null)
  36948. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36949. */
  36950. function TorusKnotGeometry(id, scene,
  36951. /**
  36952. * Defines the radius of the torus knot
  36953. */
  36954. radius,
  36955. /**
  36956. * Defines the thickness of the torus knot tube
  36957. */
  36958. tube,
  36959. /**
  36960. * Defines the number of radial segments
  36961. */
  36962. radialSegments,
  36963. /**
  36964. * Defines the number of tubular segments
  36965. */
  36966. tubularSegments,
  36967. /**
  36968. * Defines the first number of windings
  36969. */
  36970. p,
  36971. /**
  36972. * Defines the second number of windings
  36973. */
  36974. q, canBeRegenerated, mesh,
  36975. /**
  36976. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36977. */
  36978. side) {
  36979. if (mesh === void 0) { mesh = null; }
  36980. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36981. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36982. _this.radius = radius;
  36983. _this.tube = tube;
  36984. _this.radialSegments = radialSegments;
  36985. _this.tubularSegments = tubularSegments;
  36986. _this.p = p;
  36987. _this.q = q;
  36988. _this.side = side;
  36989. return _this;
  36990. }
  36991. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36992. 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 });
  36993. };
  36994. TorusKnotGeometry.prototype.copy = function (id) {
  36995. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36996. };
  36997. TorusKnotGeometry.prototype.serialize = function () {
  36998. var serializationObject = _super.prototype.serialize.call(this);
  36999. serializationObject.radius = this.radius;
  37000. serializationObject.tube = this.tube;
  37001. serializationObject.radialSegments = this.radialSegments;
  37002. serializationObject.tubularSegments = this.tubularSegments;
  37003. serializationObject.p = this.p;
  37004. serializationObject.q = this.q;
  37005. return serializationObject;
  37006. };
  37007. ;
  37008. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37009. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37010. return null; // null since geometry could be something else than a ground...
  37011. }
  37012. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37013. if (BABYLON.Tags) {
  37014. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37015. }
  37016. scene.pushGeometry(torusKnot, true);
  37017. return torusKnot;
  37018. };
  37019. return TorusKnotGeometry;
  37020. }(_PrimitiveGeometry));
  37021. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37022. //}
  37023. })(BABYLON || (BABYLON = {}));
  37024. //# sourceMappingURL=babylon.geometry.js.map
  37025. "use strict";
  37026. var BABYLON;
  37027. (function (BABYLON) {
  37028. /**
  37029. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37030. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37031. */
  37032. var PostProcessManager = /** @class */ (function () {
  37033. /**
  37034. * Creates a new instance of @see PostProcess
  37035. * @param scene The scene that the post process is associated with.
  37036. */
  37037. function PostProcessManager(scene) {
  37038. this._vertexBuffers = {};
  37039. this._scene = scene;
  37040. }
  37041. PostProcessManager.prototype._prepareBuffers = function () {
  37042. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37043. return;
  37044. }
  37045. // VBO
  37046. var vertices = [];
  37047. vertices.push(1, 1);
  37048. vertices.push(-1, 1);
  37049. vertices.push(-1, -1);
  37050. vertices.push(1, -1);
  37051. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37052. this._buildIndexBuffer();
  37053. };
  37054. PostProcessManager.prototype._buildIndexBuffer = function () {
  37055. // Indices
  37056. var indices = [];
  37057. indices.push(0);
  37058. indices.push(1);
  37059. indices.push(2);
  37060. indices.push(0);
  37061. indices.push(2);
  37062. indices.push(3);
  37063. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37064. };
  37065. /**
  37066. * Rebuilds the vertex buffers of the manager.
  37067. */
  37068. PostProcessManager.prototype._rebuild = function () {
  37069. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37070. if (!vb) {
  37071. return;
  37072. }
  37073. vb._rebuild();
  37074. this._buildIndexBuffer();
  37075. };
  37076. // Methods
  37077. /**
  37078. * Prepares a frame to be run through a post process.
  37079. * @param sourceTexture The input texture to the post procesess. (default: null)
  37080. * @param postProcesses An array of post processes to be run. (default: null)
  37081. * @returns True if the post processes were able to be run.
  37082. */
  37083. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37084. if (sourceTexture === void 0) { sourceTexture = null; }
  37085. if (postProcesses === void 0) { postProcesses = null; }
  37086. var camera = this._scene.activeCamera;
  37087. if (!camera) {
  37088. return false;
  37089. }
  37090. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37091. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37092. return false;
  37093. }
  37094. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37095. return true;
  37096. };
  37097. /**
  37098. * Manually render a set of post processes to a texture.
  37099. * @param postProcesses An array of post processes to be run.
  37100. * @param targetTexture The target texture to render to.
  37101. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37102. */
  37103. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37104. if (targetTexture === void 0) { targetTexture = null; }
  37105. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37106. var engine = this._scene.getEngine();
  37107. for (var index = 0; index < postProcesses.length; index++) {
  37108. if (index < postProcesses.length - 1) {
  37109. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37110. }
  37111. else {
  37112. if (targetTexture) {
  37113. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37114. }
  37115. else {
  37116. engine.restoreDefaultFramebuffer();
  37117. }
  37118. }
  37119. var pp = postProcesses[index];
  37120. var effect = pp.apply();
  37121. if (effect) {
  37122. pp.onBeforeRenderObservable.notifyObservers(effect);
  37123. // VBOs
  37124. this._prepareBuffers();
  37125. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37126. // Draw order
  37127. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37128. pp.onAfterRenderObservable.notifyObservers(effect);
  37129. }
  37130. }
  37131. // Restore depth buffer
  37132. engine.setDepthBuffer(true);
  37133. engine.setDepthWrite(true);
  37134. };
  37135. /**
  37136. * Finalize the result of the output of the postprocesses.
  37137. * @param doNotPresent If true the result will not be displayed to the screen.
  37138. * @param targetTexture The target texture to render to.
  37139. * @param faceIndex The index of the face to bind the target texture to.
  37140. * @param postProcesses The array of post processes to render.
  37141. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37142. */
  37143. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37144. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37145. var camera = this._scene.activeCamera;
  37146. if (!camera) {
  37147. return;
  37148. }
  37149. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37150. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37151. return;
  37152. }
  37153. var engine = this._scene.getEngine();
  37154. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37155. var pp = postProcesses[index];
  37156. if (index < len - 1) {
  37157. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37158. }
  37159. else {
  37160. if (targetTexture) {
  37161. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37162. }
  37163. else {
  37164. engine.restoreDefaultFramebuffer();
  37165. }
  37166. }
  37167. if (doNotPresent) {
  37168. break;
  37169. }
  37170. var effect = pp.apply();
  37171. if (effect) {
  37172. pp.onBeforeRenderObservable.notifyObservers(effect);
  37173. // VBOs
  37174. this._prepareBuffers();
  37175. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37176. // Draw order
  37177. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37178. pp.onAfterRenderObservable.notifyObservers(effect);
  37179. }
  37180. }
  37181. // Restore states
  37182. engine.setDepthBuffer(true);
  37183. engine.setDepthWrite(true);
  37184. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37185. };
  37186. /**
  37187. * Disposes of the post process manager.
  37188. */
  37189. PostProcessManager.prototype.dispose = function () {
  37190. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37191. if (buffer) {
  37192. buffer.dispose();
  37193. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37194. }
  37195. if (this._indexBuffer) {
  37196. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37197. this._indexBuffer = null;
  37198. }
  37199. };
  37200. return PostProcessManager;
  37201. }());
  37202. BABYLON.PostProcessManager = PostProcessManager;
  37203. })(BABYLON || (BABYLON = {}));
  37204. //# sourceMappingURL=babylon.postProcessManager.js.map
  37205. "use strict";
  37206. var BABYLON;
  37207. (function (BABYLON) {
  37208. /**
  37209. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37210. */
  37211. var PerformanceMonitor = /** @class */ (function () {
  37212. /**
  37213. * constructor
  37214. * @param frameSampleSize The number of samples required to saturate the sliding window
  37215. */
  37216. function PerformanceMonitor(frameSampleSize) {
  37217. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37218. this._enabled = true;
  37219. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37220. }
  37221. /**
  37222. * Samples current frame
  37223. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37224. */
  37225. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37226. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37227. if (!this._enabled)
  37228. return;
  37229. if (this._lastFrameTimeMs != null) {
  37230. var dt = timeMs - this._lastFrameTimeMs;
  37231. this._rollingFrameTime.add(dt);
  37232. }
  37233. this._lastFrameTimeMs = timeMs;
  37234. };
  37235. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37236. /**
  37237. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37238. * @return Average frame time in milliseconds
  37239. */
  37240. get: function () {
  37241. return this._rollingFrameTime.average;
  37242. },
  37243. enumerable: true,
  37244. configurable: true
  37245. });
  37246. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37247. /**
  37248. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37249. * @return Frame time variance in milliseconds squared
  37250. */
  37251. get: function () {
  37252. return this._rollingFrameTime.variance;
  37253. },
  37254. enumerable: true,
  37255. configurable: true
  37256. });
  37257. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37258. /**
  37259. * Returns the frame time of the most recent frame
  37260. * @return Frame time in milliseconds
  37261. */
  37262. get: function () {
  37263. return this._rollingFrameTime.history(0);
  37264. },
  37265. enumerable: true,
  37266. configurable: true
  37267. });
  37268. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37269. /**
  37270. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37271. * @return Framerate in frames per second
  37272. */
  37273. get: function () {
  37274. return 1000.0 / this._rollingFrameTime.average;
  37275. },
  37276. enumerable: true,
  37277. configurable: true
  37278. });
  37279. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37280. /**
  37281. * Returns the average framerate in frames per second using the most recent frame time
  37282. * @return Framerate in frames per second
  37283. */
  37284. get: function () {
  37285. var history = this._rollingFrameTime.history(0);
  37286. if (history === 0) {
  37287. return 0;
  37288. }
  37289. return 1000.0 / history;
  37290. },
  37291. enumerable: true,
  37292. configurable: true
  37293. });
  37294. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37295. /**
  37296. * Returns true if enough samples have been taken to completely fill the sliding window
  37297. * @return true if saturated
  37298. */
  37299. get: function () {
  37300. return this._rollingFrameTime.isSaturated();
  37301. },
  37302. enumerable: true,
  37303. configurable: true
  37304. });
  37305. /**
  37306. * Enables contributions to the sliding window sample set
  37307. */
  37308. PerformanceMonitor.prototype.enable = function () {
  37309. this._enabled = true;
  37310. };
  37311. /**
  37312. * Disables contributions to the sliding window sample set
  37313. * Samples will not be interpolated over the disabled period
  37314. */
  37315. PerformanceMonitor.prototype.disable = function () {
  37316. this._enabled = false;
  37317. //clear last sample to avoid interpolating over the disabled period when next enabled
  37318. this._lastFrameTimeMs = null;
  37319. };
  37320. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37321. /**
  37322. * Returns true if sampling is enabled
  37323. * @return true if enabled
  37324. */
  37325. get: function () {
  37326. return this._enabled;
  37327. },
  37328. enumerable: true,
  37329. configurable: true
  37330. });
  37331. /**
  37332. * Resets performance monitor
  37333. */
  37334. PerformanceMonitor.prototype.reset = function () {
  37335. //clear last sample to avoid interpolating over the disabled period when next enabled
  37336. this._lastFrameTimeMs = null;
  37337. //wipe record
  37338. this._rollingFrameTime.reset();
  37339. };
  37340. return PerformanceMonitor;
  37341. }());
  37342. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37343. /**
  37344. * RollingAverage
  37345. *
  37346. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37347. */
  37348. var RollingAverage = /** @class */ (function () {
  37349. /**
  37350. * constructor
  37351. * @param length The number of samples required to saturate the sliding window
  37352. */
  37353. function RollingAverage(length) {
  37354. this._samples = new Array(length);
  37355. this.reset();
  37356. }
  37357. /**
  37358. * Adds a sample to the sample set
  37359. * @param v The sample value
  37360. */
  37361. RollingAverage.prototype.add = function (v) {
  37362. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37363. var delta;
  37364. //we need to check if we've already wrapped round
  37365. if (this.isSaturated()) {
  37366. //remove bottom of stack from mean
  37367. var bottomValue = this._samples[this._pos];
  37368. delta = bottomValue - this.average;
  37369. this.average -= delta / (this._sampleCount - 1);
  37370. this._m2 -= delta * (bottomValue - this.average);
  37371. }
  37372. else {
  37373. this._sampleCount++;
  37374. }
  37375. //add new value to mean
  37376. delta = v - this.average;
  37377. this.average += delta / (this._sampleCount);
  37378. this._m2 += delta * (v - this.average);
  37379. //set the new variance
  37380. this.variance = this._m2 / (this._sampleCount - 1);
  37381. this._samples[this._pos] = v;
  37382. this._pos++;
  37383. this._pos %= this._samples.length; //positive wrap around
  37384. };
  37385. /**
  37386. * Returns previously added values or null if outside of history or outside the sliding window domain
  37387. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37388. * @return Value previously recorded with add() or null if outside of range
  37389. */
  37390. RollingAverage.prototype.history = function (i) {
  37391. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37392. return 0;
  37393. }
  37394. var i0 = this._wrapPosition(this._pos - 1.0);
  37395. return this._samples[this._wrapPosition(i0 - i)];
  37396. };
  37397. /**
  37398. * Returns true if enough samples have been taken to completely fill the sliding window
  37399. * @return true if sample-set saturated
  37400. */
  37401. RollingAverage.prototype.isSaturated = function () {
  37402. return this._sampleCount >= this._samples.length;
  37403. };
  37404. /**
  37405. * Resets the rolling average (equivalent to 0 samples taken so far)
  37406. */
  37407. RollingAverage.prototype.reset = function () {
  37408. this.average = 0;
  37409. this.variance = 0;
  37410. this._sampleCount = 0;
  37411. this._pos = 0;
  37412. this._m2 = 0;
  37413. };
  37414. /**
  37415. * Wraps a value around the sample range boundaries
  37416. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37417. * @return Wrapped position in sample range
  37418. */
  37419. RollingAverage.prototype._wrapPosition = function (i) {
  37420. var max = this._samples.length;
  37421. return ((i % max) + max) % max;
  37422. };
  37423. return RollingAverage;
  37424. }());
  37425. BABYLON.RollingAverage = RollingAverage;
  37426. })(BABYLON || (BABYLON = {}));
  37427. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37428. "use strict";
  37429. var BABYLON;
  37430. (function (BABYLON) {
  37431. /**
  37432. * This groups together the common properties used for image processing either in direct forward pass
  37433. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37434. * or not.
  37435. */
  37436. var ImageProcessingConfiguration = /** @class */ (function () {
  37437. function ImageProcessingConfiguration() {
  37438. /**
  37439. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37440. */
  37441. this.colorCurves = new BABYLON.ColorCurves();
  37442. this._colorCurvesEnabled = false;
  37443. this._colorGradingEnabled = false;
  37444. this._colorGradingWithGreenDepth = true;
  37445. this._colorGradingBGR = true;
  37446. this._exposure = 1.0;
  37447. this._toneMappingEnabled = false;
  37448. this._contrast = 1.0;
  37449. /**
  37450. * Vignette stretch size.
  37451. */
  37452. this.vignetteStretch = 0;
  37453. /**
  37454. * Vignette centre X Offset.
  37455. */
  37456. this.vignetteCentreX = 0;
  37457. /**
  37458. * Vignette centre Y Offset.
  37459. */
  37460. this.vignetteCentreY = 0;
  37461. /**
  37462. * Vignette weight or intensity of the vignette effect.
  37463. */
  37464. this.vignetteWeight = 1.5;
  37465. /**
  37466. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37467. * if vignetteEnabled is set to true.
  37468. */
  37469. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37470. /**
  37471. * Camera field of view used by the Vignette effect.
  37472. */
  37473. this.vignetteCameraFov = 0.5;
  37474. this._grainEnabled = false;
  37475. this._grainIntensity = 30;
  37476. this._grainAnimated = false;
  37477. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37478. this._vignetteEnabled = false;
  37479. this._applyByPostProcess = false;
  37480. this._isEnabled = true;
  37481. /**
  37482. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37483. * @type {BABYLON.Observable}
  37484. */
  37485. this.onUpdateParameters = new BABYLON.Observable();
  37486. }
  37487. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37488. /**
  37489. * Gets wether the color curves effect is enabled.
  37490. */
  37491. get: function () {
  37492. return this._colorCurvesEnabled;
  37493. },
  37494. /**
  37495. * Sets wether the color curves effect is enabled.
  37496. */
  37497. set: function (value) {
  37498. if (this._colorCurvesEnabled === value) {
  37499. return;
  37500. }
  37501. this._colorCurvesEnabled = value;
  37502. this._updateParameters();
  37503. },
  37504. enumerable: true,
  37505. configurable: true
  37506. });
  37507. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37508. /**
  37509. * Gets wether the color grading effect is enabled.
  37510. */
  37511. get: function () {
  37512. return this._colorGradingEnabled;
  37513. },
  37514. /**
  37515. * Sets wether the color grading effect is enabled.
  37516. */
  37517. set: function (value) {
  37518. if (this._colorGradingEnabled === value) {
  37519. return;
  37520. }
  37521. this._colorGradingEnabled = value;
  37522. this._updateParameters();
  37523. },
  37524. enumerable: true,
  37525. configurable: true
  37526. });
  37527. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37528. /**
  37529. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37530. */
  37531. get: function () {
  37532. return this._colorGradingWithGreenDepth;
  37533. },
  37534. /**
  37535. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37536. */
  37537. set: function (value) {
  37538. if (this._colorGradingWithGreenDepth === value) {
  37539. return;
  37540. }
  37541. this._colorGradingWithGreenDepth = value;
  37542. this._updateParameters();
  37543. },
  37544. enumerable: true,
  37545. configurable: true
  37546. });
  37547. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37548. /**
  37549. * Gets wether the color grading texture contains BGR values.
  37550. */
  37551. get: function () {
  37552. return this._colorGradingBGR;
  37553. },
  37554. /**
  37555. * Sets wether the color grading texture contains BGR values.
  37556. */
  37557. set: function (value) {
  37558. if (this._colorGradingBGR === value) {
  37559. return;
  37560. }
  37561. this._colorGradingBGR = value;
  37562. this._updateParameters();
  37563. },
  37564. enumerable: true,
  37565. configurable: true
  37566. });
  37567. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37568. /**
  37569. * Gets the Exposure used in the effect.
  37570. */
  37571. get: function () {
  37572. return this._exposure;
  37573. },
  37574. /**
  37575. * Sets the Exposure used in the effect.
  37576. */
  37577. set: function (value) {
  37578. if (this._exposure === value) {
  37579. return;
  37580. }
  37581. this._exposure = value;
  37582. this._updateParameters();
  37583. },
  37584. enumerable: true,
  37585. configurable: true
  37586. });
  37587. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37588. /**
  37589. * Gets wether the tone mapping effect is enabled.
  37590. */
  37591. get: function () {
  37592. return this._toneMappingEnabled;
  37593. },
  37594. /**
  37595. * Sets wether the tone mapping effect is enabled.
  37596. */
  37597. set: function (value) {
  37598. if (this._toneMappingEnabled === value) {
  37599. return;
  37600. }
  37601. this._toneMappingEnabled = value;
  37602. this._updateParameters();
  37603. },
  37604. enumerable: true,
  37605. configurable: true
  37606. });
  37607. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37608. /**
  37609. * Gets the contrast used in the effect.
  37610. */
  37611. get: function () {
  37612. return this._contrast;
  37613. },
  37614. /**
  37615. * Sets the contrast used in the effect.
  37616. */
  37617. set: function (value) {
  37618. if (this._contrast === value) {
  37619. return;
  37620. }
  37621. this._contrast = value;
  37622. this._updateParameters();
  37623. },
  37624. enumerable: true,
  37625. configurable: true
  37626. });
  37627. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37628. /**
  37629. * If the grain effect should be enabled.
  37630. */
  37631. get: function () {
  37632. return this._grainEnabled;
  37633. },
  37634. set: function (value) {
  37635. if (this._grainEnabled === value) {
  37636. return;
  37637. }
  37638. this._grainEnabled = value;
  37639. this._updateParameters();
  37640. },
  37641. enumerable: true,
  37642. configurable: true
  37643. });
  37644. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37645. /**
  37646. * Amount of grain to be applied by the grain effect.
  37647. */
  37648. get: function () {
  37649. return this._grainIntensity;
  37650. },
  37651. set: function (value) {
  37652. if (this._grainIntensity === value) {
  37653. return;
  37654. }
  37655. this._grainIntensity = value;
  37656. },
  37657. enumerable: true,
  37658. configurable: true
  37659. });
  37660. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37661. /**
  37662. * If the grain effect should be animated.
  37663. */
  37664. get: function () {
  37665. return this._grainAnimated;
  37666. },
  37667. set: function (value) {
  37668. if (this._grainAnimated === value) {
  37669. return;
  37670. }
  37671. this._grainAnimated = value;
  37672. this._updateParameters();
  37673. },
  37674. enumerable: true,
  37675. configurable: true
  37676. });
  37677. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37678. /**
  37679. * Gets the vignette blend mode allowing different kind of effect.
  37680. */
  37681. get: function () {
  37682. return this._vignetteBlendMode;
  37683. },
  37684. /**
  37685. * Sets the vignette blend mode allowing different kind of effect.
  37686. */
  37687. set: function (value) {
  37688. if (this._vignetteBlendMode === value) {
  37689. return;
  37690. }
  37691. this._vignetteBlendMode = value;
  37692. this._updateParameters();
  37693. },
  37694. enumerable: true,
  37695. configurable: true
  37696. });
  37697. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37698. /**
  37699. * Gets wether the vignette effect is enabled.
  37700. */
  37701. get: function () {
  37702. return this._vignetteEnabled;
  37703. },
  37704. /**
  37705. * Sets wether the vignette effect is enabled.
  37706. */
  37707. set: function (value) {
  37708. if (this._vignetteEnabled === value) {
  37709. return;
  37710. }
  37711. this._vignetteEnabled = value;
  37712. this._updateParameters();
  37713. },
  37714. enumerable: true,
  37715. configurable: true
  37716. });
  37717. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37718. /**
  37719. * Gets wether the image processing is applied through a post process or not.
  37720. */
  37721. get: function () {
  37722. return this._applyByPostProcess;
  37723. },
  37724. /**
  37725. * Sets wether the image processing is applied through a post process or not.
  37726. */
  37727. set: function (value) {
  37728. if (this._applyByPostProcess === value) {
  37729. return;
  37730. }
  37731. this._applyByPostProcess = value;
  37732. this._updateParameters();
  37733. },
  37734. enumerable: true,
  37735. configurable: true
  37736. });
  37737. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37738. /**
  37739. * Gets wether the image processing is enabled or not.
  37740. */
  37741. get: function () {
  37742. return this._isEnabled;
  37743. },
  37744. /**
  37745. * Sets wether the image processing is enabled or not.
  37746. */
  37747. set: function (value) {
  37748. if (this._isEnabled === value) {
  37749. return;
  37750. }
  37751. this._isEnabled = value;
  37752. this._updateParameters();
  37753. },
  37754. enumerable: true,
  37755. configurable: true
  37756. });
  37757. /**
  37758. * Method called each time the image processing information changes requires to recompile the effect.
  37759. */
  37760. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37761. this.onUpdateParameters.notifyObservers(this);
  37762. };
  37763. ImageProcessingConfiguration.prototype.getClassName = function () {
  37764. return "ImageProcessingConfiguration";
  37765. };
  37766. /**
  37767. * Prepare the list of uniforms associated with the Image Processing effects.
  37768. * @param uniformsList The list of uniforms used in the effect
  37769. * @param defines the list of defines currently in use
  37770. */
  37771. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37772. if (defines.EXPOSURE) {
  37773. uniforms.push("exposureLinear");
  37774. }
  37775. if (defines.CONTRAST) {
  37776. uniforms.push("contrast");
  37777. }
  37778. if (defines.COLORGRADING) {
  37779. uniforms.push("colorTransformSettings");
  37780. }
  37781. if (defines.VIGNETTE) {
  37782. uniforms.push("vInverseScreenSize");
  37783. uniforms.push("vignetteSettings1");
  37784. uniforms.push("vignetteSettings2");
  37785. }
  37786. if (defines.COLORCURVES) {
  37787. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37788. }
  37789. if (defines.GRAIN) {
  37790. uniforms.push("grainVarianceAmount");
  37791. uniforms.push("grainAnimatedSeed");
  37792. }
  37793. };
  37794. /**
  37795. * Prepare the list of samplers associated with the Image Processing effects.
  37796. * @param uniformsList The list of uniforms used in the effect
  37797. * @param defines the list of defines currently in use
  37798. */
  37799. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37800. if (defines.COLORGRADING) {
  37801. samplersList.push("txColorTransform");
  37802. }
  37803. };
  37804. /**
  37805. * Prepare the list of defines associated to the shader.
  37806. * @param defines the list of defines to complete
  37807. */
  37808. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37809. if (forPostProcess === void 0) { forPostProcess = false; }
  37810. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37811. defines.VIGNETTE = false;
  37812. defines.TONEMAPPING = false;
  37813. defines.CONTRAST = false;
  37814. defines.EXPOSURE = false;
  37815. defines.COLORCURVES = false;
  37816. defines.COLORGRADING = false;
  37817. defines.COLORGRADING3D = false;
  37818. defines.IMAGEPROCESSING = false;
  37819. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37820. return;
  37821. }
  37822. defines.VIGNETTE = this.vignetteEnabled;
  37823. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37824. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37825. defines.TONEMAPPING = this.toneMappingEnabled;
  37826. defines.CONTRAST = (this.contrast !== 1.0);
  37827. defines.EXPOSURE = (this.exposure !== 1.0);
  37828. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37829. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37830. if (defines.COLORGRADING) {
  37831. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37832. }
  37833. else {
  37834. defines.COLORGRADING3D = false;
  37835. }
  37836. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37837. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37838. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37839. defines.GRAIN = this.grainEnabled;
  37840. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37841. };
  37842. /**
  37843. * Returns true if all the image processing information are ready.
  37844. */
  37845. ImageProcessingConfiguration.prototype.isReady = function () {
  37846. // Color Grading texure can not be none blocking.
  37847. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37848. };
  37849. /**
  37850. * Binds the image processing to the shader.
  37851. * @param effect The effect to bind to
  37852. */
  37853. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37854. if (aspectRatio === void 0) { aspectRatio = 1; }
  37855. // Color Curves
  37856. if (this._colorCurvesEnabled && this.colorCurves) {
  37857. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37858. }
  37859. // Vignette
  37860. if (this._vignetteEnabled) {
  37861. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37862. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37863. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37864. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37865. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37866. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37867. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37868. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37869. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37870. var vignettePower = -2.0 * this.vignetteWeight;
  37871. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37872. }
  37873. // Exposure
  37874. effect.setFloat("exposureLinear", this.exposure);
  37875. // Contrast
  37876. effect.setFloat("contrast", this.contrast);
  37877. // Color transform settings
  37878. if (this.colorGradingTexture) {
  37879. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37880. var textureSize = this.colorGradingTexture.getSize().height;
  37881. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37882. 0.5 / textureSize, // textureOffset
  37883. textureSize, // textureSize
  37884. this.colorGradingTexture.level // weight
  37885. );
  37886. }
  37887. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37888. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37889. };
  37890. /**
  37891. * Clones the current image processing instance.
  37892. * @return The cloned image processing
  37893. */
  37894. ImageProcessingConfiguration.prototype.clone = function () {
  37895. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37896. };
  37897. /**
  37898. * Serializes the current image processing instance to a json representation.
  37899. * @return a JSON representation
  37900. */
  37901. ImageProcessingConfiguration.prototype.serialize = function () {
  37902. return BABYLON.SerializationHelper.Serialize(this);
  37903. };
  37904. /**
  37905. * Parses the image processing from a json representation.
  37906. * @param source the JSON source to parse
  37907. * @return The parsed image processing
  37908. */
  37909. ImageProcessingConfiguration.Parse = function (source) {
  37910. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37911. };
  37912. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37913. /**
  37914. * Used to apply the vignette as a mix with the pixel color.
  37915. */
  37916. get: function () {
  37917. return this._VIGNETTEMODE_MULTIPLY;
  37918. },
  37919. enumerable: true,
  37920. configurable: true
  37921. });
  37922. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37923. /**
  37924. * Used to apply the vignette as a replacement of the pixel color.
  37925. */
  37926. get: function () {
  37927. return this._VIGNETTEMODE_OPAQUE;
  37928. },
  37929. enumerable: true,
  37930. configurable: true
  37931. });
  37932. // Static constants associated to the image processing.
  37933. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37934. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37935. __decorate([
  37936. BABYLON.serializeAsColorCurves()
  37937. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37938. __decorate([
  37939. BABYLON.serialize()
  37940. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37941. __decorate([
  37942. BABYLON.serializeAsTexture()
  37943. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37944. __decorate([
  37945. BABYLON.serialize()
  37946. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37947. __decorate([
  37948. BABYLON.serialize()
  37949. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37950. __decorate([
  37951. BABYLON.serialize()
  37952. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37953. __decorate([
  37954. BABYLON.serialize()
  37955. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37956. __decorate([
  37957. BABYLON.serialize()
  37958. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37959. __decorate([
  37960. BABYLON.serialize()
  37961. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37962. __decorate([
  37963. BABYLON.serialize()
  37964. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37965. __decorate([
  37966. BABYLON.serialize()
  37967. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37968. __decorate([
  37969. BABYLON.serialize()
  37970. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37971. __decorate([
  37972. BABYLON.serialize()
  37973. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37974. __decorate([
  37975. BABYLON.serializeAsColor4()
  37976. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37977. __decorate([
  37978. BABYLON.serialize()
  37979. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37980. __decorate([
  37981. BABYLON.serialize()
  37982. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37983. __decorate([
  37984. BABYLON.serialize()
  37985. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37986. __decorate([
  37987. BABYLON.serialize()
  37988. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37989. __decorate([
  37990. BABYLON.serialize()
  37991. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37992. __decorate([
  37993. BABYLON.serialize()
  37994. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37995. __decorate([
  37996. BABYLON.serialize()
  37997. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37998. __decorate([
  37999. BABYLON.serialize()
  38000. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38001. return ImageProcessingConfiguration;
  38002. }());
  38003. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38004. })(BABYLON || (BABYLON = {}));
  38005. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38006. "use strict";
  38007. var BABYLON;
  38008. (function (BABYLON) {
  38009. /**
  38010. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38011. * It can help converting any input color in a desired output one. This can then be used to create effects
  38012. * from sepia, black and white to sixties or futuristic rendering...
  38013. *
  38014. * The only supported format is currently 3dl.
  38015. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38016. */
  38017. var ColorGradingTexture = /** @class */ (function (_super) {
  38018. __extends(ColorGradingTexture, _super);
  38019. /**
  38020. * Instantiates a ColorGradingTexture from the following parameters.
  38021. *
  38022. * @param url The location of the color gradind data (currently only supporting 3dl)
  38023. * @param scene The scene the texture will be used in
  38024. */
  38025. function ColorGradingTexture(url, scene) {
  38026. var _this = _super.call(this, scene) || this;
  38027. if (!url) {
  38028. return _this;
  38029. }
  38030. _this._engine = scene.getEngine();
  38031. _this._textureMatrix = BABYLON.Matrix.Identity();
  38032. _this.name = url;
  38033. _this.url = url;
  38034. _this.hasAlpha = false;
  38035. _this.isCube = false;
  38036. _this.is3D = _this._engine.webGLVersion > 1;
  38037. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38038. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38039. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38040. _this.anisotropicFilteringLevel = 1;
  38041. _this._texture = _this._getFromCache(url, true);
  38042. if (!_this._texture) {
  38043. if (!scene.useDelayedTextureLoading) {
  38044. _this.loadTexture();
  38045. }
  38046. else {
  38047. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38048. }
  38049. }
  38050. return _this;
  38051. }
  38052. /**
  38053. * Returns the texture matrix used in most of the material.
  38054. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38055. */
  38056. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38057. return this._textureMatrix;
  38058. };
  38059. /**
  38060. * Occurs when the file being loaded is a .3dl LUT file.
  38061. */
  38062. ColorGradingTexture.prototype.load3dlTexture = function () {
  38063. var engine = this._engine;
  38064. var texture;
  38065. if (engine.webGLVersion === 1) {
  38066. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38067. }
  38068. else {
  38069. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38070. }
  38071. this._texture = texture;
  38072. var callback = function (text) {
  38073. if (typeof text !== "string") {
  38074. return;
  38075. }
  38076. var data = null;
  38077. var tempData = null;
  38078. var line;
  38079. var lines = text.split('\n');
  38080. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38081. var maxColor = 0;
  38082. for (var i = 0; i < lines.length; i++) {
  38083. line = lines[i];
  38084. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38085. continue;
  38086. if (line.indexOf('#') === 0)
  38087. continue;
  38088. var words = line.split(" ");
  38089. if (size === 0) {
  38090. // Number of space + one
  38091. size = words.length;
  38092. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38093. tempData = new Float32Array(size * size * size * 4);
  38094. continue;
  38095. }
  38096. if (size != 0) {
  38097. var r = Math.max(parseInt(words[0]), 0);
  38098. var g = Math.max(parseInt(words[1]), 0);
  38099. var b = Math.max(parseInt(words[2]), 0);
  38100. maxColor = Math.max(r, maxColor);
  38101. maxColor = Math.max(g, maxColor);
  38102. maxColor = Math.max(b, maxColor);
  38103. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38104. if (tempData) {
  38105. tempData[pixelStorageIndex + 0] = r;
  38106. tempData[pixelStorageIndex + 1] = g;
  38107. tempData[pixelStorageIndex + 2] = b;
  38108. }
  38109. pixelIndexSlice++;
  38110. if (pixelIndexSlice % size == 0) {
  38111. pixelIndexH++;
  38112. pixelIndexSlice = 0;
  38113. if (pixelIndexH % size == 0) {
  38114. pixelIndexW++;
  38115. pixelIndexH = 0;
  38116. }
  38117. }
  38118. }
  38119. }
  38120. if (tempData && data) {
  38121. for (var i = 0; i < tempData.length; i++) {
  38122. if (i > 0 && (i + 1) % 4 === 0) {
  38123. data[i] = 255;
  38124. }
  38125. else {
  38126. var value = tempData[i];
  38127. data[i] = (value / maxColor * 255);
  38128. }
  38129. }
  38130. }
  38131. if (texture.is3D) {
  38132. texture.updateSize(size, size, size);
  38133. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38134. }
  38135. else {
  38136. texture.updateSize(size * size, size);
  38137. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38138. }
  38139. };
  38140. var scene = this.getScene();
  38141. if (scene) {
  38142. scene._loadFile(this.url, callback);
  38143. }
  38144. else {
  38145. this._engine._loadFile(this.url, callback);
  38146. }
  38147. return this._texture;
  38148. };
  38149. /**
  38150. * Starts the loading process of the texture.
  38151. */
  38152. ColorGradingTexture.prototype.loadTexture = function () {
  38153. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38154. this.load3dlTexture();
  38155. }
  38156. };
  38157. /**
  38158. * Clones the color gradind texture.
  38159. */
  38160. ColorGradingTexture.prototype.clone = function () {
  38161. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38162. // Base texture
  38163. newTexture.level = this.level;
  38164. return newTexture;
  38165. };
  38166. /**
  38167. * Called during delayed load for textures.
  38168. */
  38169. ColorGradingTexture.prototype.delayLoad = function () {
  38170. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38171. return;
  38172. }
  38173. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38174. this._texture = this._getFromCache(this.url, true);
  38175. if (!this._texture) {
  38176. this.loadTexture();
  38177. }
  38178. };
  38179. /**
  38180. * Parses a color grading texture serialized by Babylon.
  38181. * @param parsedTexture The texture information being parsedTexture
  38182. * @param scene The scene to load the texture in
  38183. * @param rootUrl The root url of the data assets to load
  38184. * @return A color gradind texture
  38185. */
  38186. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38187. var texture = null;
  38188. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38189. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38190. texture.name = parsedTexture.name;
  38191. texture.level = parsedTexture.level;
  38192. }
  38193. return texture;
  38194. };
  38195. /**
  38196. * Serializes the LUT texture to json format.
  38197. */
  38198. ColorGradingTexture.prototype.serialize = function () {
  38199. if (!this.name) {
  38200. return null;
  38201. }
  38202. var serializationObject = {};
  38203. serializationObject.name = this.name;
  38204. serializationObject.level = this.level;
  38205. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38206. return serializationObject;
  38207. };
  38208. /**
  38209. * Empty line regex stored for GC.
  38210. */
  38211. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38212. return ColorGradingTexture;
  38213. }(BABYLON.BaseTexture));
  38214. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38215. })(BABYLON || (BABYLON = {}));
  38216. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38217. "use strict";
  38218. var BABYLON;
  38219. (function (BABYLON) {
  38220. /**
  38221. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38222. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38223. * 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;
  38224. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38225. */
  38226. var ColorCurves = /** @class */ (function () {
  38227. function ColorCurves() {
  38228. this._dirty = true;
  38229. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38230. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38231. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38232. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38233. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38234. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38235. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38236. this._globalHue = 30;
  38237. this._globalDensity = 0;
  38238. this._globalSaturation = 0;
  38239. this._globalExposure = 0;
  38240. this._highlightsHue = 30;
  38241. this._highlightsDensity = 0;
  38242. this._highlightsSaturation = 0;
  38243. this._highlightsExposure = 0;
  38244. this._midtonesHue = 30;
  38245. this._midtonesDensity = 0;
  38246. this._midtonesSaturation = 0;
  38247. this._midtonesExposure = 0;
  38248. this._shadowsHue = 30;
  38249. this._shadowsDensity = 0;
  38250. this._shadowsSaturation = 0;
  38251. this._shadowsExposure = 0;
  38252. }
  38253. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38254. /**
  38255. * Gets the global Hue value.
  38256. * 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).
  38257. */
  38258. get: function () {
  38259. return this._globalHue;
  38260. },
  38261. /**
  38262. * Sets the global Hue value.
  38263. * 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).
  38264. */
  38265. set: function (value) {
  38266. this._globalHue = value;
  38267. this._dirty = true;
  38268. },
  38269. enumerable: true,
  38270. configurable: true
  38271. });
  38272. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38273. /**
  38274. * Gets the global Density value.
  38275. * 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.
  38276. * Values less than zero provide a filter of opposite hue.
  38277. */
  38278. get: function () {
  38279. return this._globalDensity;
  38280. },
  38281. /**
  38282. * Sets the global Density value.
  38283. * 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.
  38284. * Values less than zero provide a filter of opposite hue.
  38285. */
  38286. set: function (value) {
  38287. this._globalDensity = value;
  38288. this._dirty = true;
  38289. },
  38290. enumerable: true,
  38291. configurable: true
  38292. });
  38293. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38294. /**
  38295. * Gets the global Saturation value.
  38296. * 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.
  38297. */
  38298. get: function () {
  38299. return this._globalSaturation;
  38300. },
  38301. /**
  38302. * Sets the global Saturation value.
  38303. * 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.
  38304. */
  38305. set: function (value) {
  38306. this._globalSaturation = value;
  38307. this._dirty = true;
  38308. },
  38309. enumerable: true,
  38310. configurable: true
  38311. });
  38312. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38313. /**
  38314. * Gets the highlights Hue value.
  38315. * 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).
  38316. */
  38317. get: function () {
  38318. return this._highlightsHue;
  38319. },
  38320. /**
  38321. * Sets the highlights Hue value.
  38322. * 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).
  38323. */
  38324. set: function (value) {
  38325. this._highlightsHue = value;
  38326. this._dirty = true;
  38327. },
  38328. enumerable: true,
  38329. configurable: true
  38330. });
  38331. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38332. /**
  38333. * Gets the highlights Density value.
  38334. * 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.
  38335. * Values less than zero provide a filter of opposite hue.
  38336. */
  38337. get: function () {
  38338. return this._highlightsDensity;
  38339. },
  38340. /**
  38341. * Sets the highlights Density value.
  38342. * 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.
  38343. * Values less than zero provide a filter of opposite hue.
  38344. */
  38345. set: function (value) {
  38346. this._highlightsDensity = value;
  38347. this._dirty = true;
  38348. },
  38349. enumerable: true,
  38350. configurable: true
  38351. });
  38352. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38353. /**
  38354. * Gets the highlights Saturation value.
  38355. * 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.
  38356. */
  38357. get: function () {
  38358. return this._highlightsSaturation;
  38359. },
  38360. /**
  38361. * Sets the highlights Saturation value.
  38362. * 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.
  38363. */
  38364. set: function (value) {
  38365. this._highlightsSaturation = value;
  38366. this._dirty = true;
  38367. },
  38368. enumerable: true,
  38369. configurable: true
  38370. });
  38371. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38372. /**
  38373. * Gets the highlights Exposure value.
  38374. * 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.
  38375. */
  38376. get: function () {
  38377. return this._highlightsExposure;
  38378. },
  38379. /**
  38380. * Sets the highlights Exposure value.
  38381. * 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.
  38382. */
  38383. set: function (value) {
  38384. this._highlightsExposure = value;
  38385. this._dirty = true;
  38386. },
  38387. enumerable: true,
  38388. configurable: true
  38389. });
  38390. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38391. /**
  38392. * Gets the midtones Hue value.
  38393. * 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).
  38394. */
  38395. get: function () {
  38396. return this._midtonesHue;
  38397. },
  38398. /**
  38399. * Sets the midtones Hue value.
  38400. * 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).
  38401. */
  38402. set: function (value) {
  38403. this._midtonesHue = value;
  38404. this._dirty = true;
  38405. },
  38406. enumerable: true,
  38407. configurable: true
  38408. });
  38409. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38410. /**
  38411. * Gets the midtones Density value.
  38412. * 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.
  38413. * Values less than zero provide a filter of opposite hue.
  38414. */
  38415. get: function () {
  38416. return this._midtonesDensity;
  38417. },
  38418. /**
  38419. * Sets the midtones Density value.
  38420. * 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.
  38421. * Values less than zero provide a filter of opposite hue.
  38422. */
  38423. set: function (value) {
  38424. this._midtonesDensity = value;
  38425. this._dirty = true;
  38426. },
  38427. enumerable: true,
  38428. configurable: true
  38429. });
  38430. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38431. /**
  38432. * Gets the midtones Saturation value.
  38433. * 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.
  38434. */
  38435. get: function () {
  38436. return this._midtonesSaturation;
  38437. },
  38438. /**
  38439. * Sets the midtones Saturation value.
  38440. * 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.
  38441. */
  38442. set: function (value) {
  38443. this._midtonesSaturation = value;
  38444. this._dirty = true;
  38445. },
  38446. enumerable: true,
  38447. configurable: true
  38448. });
  38449. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38450. /**
  38451. * Gets the midtones Exposure value.
  38452. * 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.
  38453. */
  38454. get: function () {
  38455. return this._midtonesExposure;
  38456. },
  38457. /**
  38458. * Sets the midtones Exposure value.
  38459. * 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.
  38460. */
  38461. set: function (value) {
  38462. this._midtonesExposure = value;
  38463. this._dirty = true;
  38464. },
  38465. enumerable: true,
  38466. configurable: true
  38467. });
  38468. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38469. /**
  38470. * Gets the shadows Hue value.
  38471. * 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).
  38472. */
  38473. get: function () {
  38474. return this._shadowsHue;
  38475. },
  38476. /**
  38477. * Sets the shadows Hue value.
  38478. * 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).
  38479. */
  38480. set: function (value) {
  38481. this._shadowsHue = value;
  38482. this._dirty = true;
  38483. },
  38484. enumerable: true,
  38485. configurable: true
  38486. });
  38487. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38488. /**
  38489. * Gets the shadows Density value.
  38490. * 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.
  38491. * Values less than zero provide a filter of opposite hue.
  38492. */
  38493. get: function () {
  38494. return this._shadowsDensity;
  38495. },
  38496. /**
  38497. * Sets the shadows Density value.
  38498. * 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.
  38499. * Values less than zero provide a filter of opposite hue.
  38500. */
  38501. set: function (value) {
  38502. this._shadowsDensity = value;
  38503. this._dirty = true;
  38504. },
  38505. enumerable: true,
  38506. configurable: true
  38507. });
  38508. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38509. /**
  38510. * Gets the shadows Saturation value.
  38511. * 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.
  38512. */
  38513. get: function () {
  38514. return this._shadowsSaturation;
  38515. },
  38516. /**
  38517. * Sets the shadows Saturation value.
  38518. * 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.
  38519. */
  38520. set: function (value) {
  38521. this._shadowsSaturation = value;
  38522. this._dirty = true;
  38523. },
  38524. enumerable: true,
  38525. configurable: true
  38526. });
  38527. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38528. /**
  38529. * Gets the shadows Exposure value.
  38530. * 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.
  38531. */
  38532. get: function () {
  38533. return this._shadowsExposure;
  38534. },
  38535. /**
  38536. * Sets the shadows Exposure value.
  38537. * 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.
  38538. */
  38539. set: function (value) {
  38540. this._shadowsExposure = value;
  38541. this._dirty = true;
  38542. },
  38543. enumerable: true,
  38544. configurable: true
  38545. });
  38546. ColorCurves.prototype.getClassName = function () {
  38547. return "ColorCurves";
  38548. };
  38549. /**
  38550. * Binds the color curves to the shader.
  38551. * @param colorCurves The color curve to bind
  38552. * @param effect The effect to bind to
  38553. */
  38554. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38555. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38556. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38557. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38558. if (colorCurves._dirty) {
  38559. colorCurves._dirty = false;
  38560. // Fill in global info.
  38561. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38562. // Compute highlights info.
  38563. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38564. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38565. // Compute midtones info.
  38566. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38567. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38568. // Compute shadows info.
  38569. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38570. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38571. // Compute deltas (neutral is midtones).
  38572. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38573. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38574. }
  38575. if (effect) {
  38576. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38577. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38578. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38579. }
  38580. };
  38581. /**
  38582. * Prepare the list of uniforms associated with the ColorCurves effects.
  38583. * @param uniformsList The list of uniforms used in the effect
  38584. */
  38585. ColorCurves.PrepareUniforms = function (uniformsList) {
  38586. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38587. };
  38588. /**
  38589. * Returns color grading data based on a hue, density, saturation and exposure value.
  38590. * @param filterHue The hue of the color filter.
  38591. * @param filterDensity The density of the color filter.
  38592. * @param saturation The saturation.
  38593. * @param exposure The exposure.
  38594. * @param result The result data container.
  38595. */
  38596. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38597. if (hue == null) {
  38598. return;
  38599. }
  38600. hue = ColorCurves.clamp(hue, 0, 360);
  38601. density = ColorCurves.clamp(density, -100, 100);
  38602. saturation = ColorCurves.clamp(saturation, -100, 100);
  38603. exposure = ColorCurves.clamp(exposure, -100, 100);
  38604. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38605. // so that the maximum filter density is only 50% control. This provides fine control
  38606. // for small values and reasonable range.
  38607. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38608. density *= 0.5;
  38609. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38610. if (density < 0) {
  38611. density *= -1;
  38612. hue = (hue + 180) % 360;
  38613. }
  38614. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38615. result.scaleToRef(2, result);
  38616. result.a = 1 + 0.01 * saturation;
  38617. };
  38618. /**
  38619. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38620. * @param value The input slider value in range [-100,100].
  38621. * @returns Adjusted value.
  38622. */
  38623. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38624. value /= 100;
  38625. var x = Math.abs(value);
  38626. x = Math.pow(x, 2);
  38627. if (value < 0) {
  38628. x *= -1;
  38629. }
  38630. x *= 100;
  38631. return x;
  38632. };
  38633. /**
  38634. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38635. * @param hue The hue (H) input.
  38636. * @param saturation The saturation (S) input.
  38637. * @param brightness The brightness (B) input.
  38638. * @result An RGBA color represented as Vector4.
  38639. */
  38640. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38641. var h = ColorCurves.clamp(hue, 0, 360);
  38642. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38643. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38644. if (s === 0) {
  38645. result.r = v;
  38646. result.g = v;
  38647. result.b = v;
  38648. }
  38649. else {
  38650. // sector 0 to 5
  38651. h /= 60;
  38652. var i = Math.floor(h);
  38653. // fractional part of h
  38654. var f = h - i;
  38655. var p = v * (1 - s);
  38656. var q = v * (1 - s * f);
  38657. var t = v * (1 - s * (1 - f));
  38658. switch (i) {
  38659. case 0:
  38660. result.r = v;
  38661. result.g = t;
  38662. result.b = p;
  38663. break;
  38664. case 1:
  38665. result.r = q;
  38666. result.g = v;
  38667. result.b = p;
  38668. break;
  38669. case 2:
  38670. result.r = p;
  38671. result.g = v;
  38672. result.b = t;
  38673. break;
  38674. case 3:
  38675. result.r = p;
  38676. result.g = q;
  38677. result.b = v;
  38678. break;
  38679. case 4:
  38680. result.r = t;
  38681. result.g = p;
  38682. result.b = v;
  38683. break;
  38684. default:// case 5:
  38685. result.r = v;
  38686. result.g = p;
  38687. result.b = q;
  38688. break;
  38689. }
  38690. }
  38691. result.a = 1;
  38692. };
  38693. /**
  38694. * Returns a value clamped between min and max
  38695. * @param value The value to clamp
  38696. * @param min The minimum of value
  38697. * @param max The maximum of value
  38698. * @returns The clamped value.
  38699. */
  38700. ColorCurves.clamp = function (value, min, max) {
  38701. return Math.min(Math.max(value, min), max);
  38702. };
  38703. /**
  38704. * Clones the current color curve instance.
  38705. * @return The cloned curves
  38706. */
  38707. ColorCurves.prototype.clone = function () {
  38708. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38709. };
  38710. /**
  38711. * Serializes the current color curve instance to a json representation.
  38712. * @return a JSON representation
  38713. */
  38714. ColorCurves.prototype.serialize = function () {
  38715. return BABYLON.SerializationHelper.Serialize(this);
  38716. };
  38717. /**
  38718. * Parses the color curve from a json representation.
  38719. * @param source the JSON source to parse
  38720. * @return The parsed curves
  38721. */
  38722. ColorCurves.Parse = function (source) {
  38723. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38724. };
  38725. __decorate([
  38726. BABYLON.serialize()
  38727. ], ColorCurves.prototype, "_globalHue", void 0);
  38728. __decorate([
  38729. BABYLON.serialize()
  38730. ], ColorCurves.prototype, "_globalDensity", void 0);
  38731. __decorate([
  38732. BABYLON.serialize()
  38733. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38734. __decorate([
  38735. BABYLON.serialize()
  38736. ], ColorCurves.prototype, "_globalExposure", void 0);
  38737. __decorate([
  38738. BABYLON.serialize()
  38739. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38740. __decorate([
  38741. BABYLON.serialize()
  38742. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38743. __decorate([
  38744. BABYLON.serialize()
  38745. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38746. __decorate([
  38747. BABYLON.serialize()
  38748. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38749. __decorate([
  38750. BABYLON.serialize()
  38751. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38752. __decorate([
  38753. BABYLON.serialize()
  38754. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38755. __decorate([
  38756. BABYLON.serialize()
  38757. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38758. __decorate([
  38759. BABYLON.serialize()
  38760. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38761. return ColorCurves;
  38762. }());
  38763. BABYLON.ColorCurves = ColorCurves;
  38764. })(BABYLON || (BABYLON = {}));
  38765. //# sourceMappingURL=babylon.colorCurves.js.map
  38766. "use strict";
  38767. //# sourceMappingURL=babylon.behavior.js.map
  38768. "use strict";
  38769. var BABYLON;
  38770. (function (BABYLON) {
  38771. /**
  38772. * "Static Class" containing the most commonly used helper while dealing with material for
  38773. * rendering purpose.
  38774. *
  38775. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38776. *
  38777. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38778. */
  38779. var MaterialHelper = /** @class */ (function () {
  38780. function MaterialHelper() {
  38781. }
  38782. /**
  38783. * Bind the current view position to an effect.
  38784. * @param effect The effect to be bound
  38785. * @param scene The scene the eyes position is used from
  38786. */
  38787. MaterialHelper.BindEyePosition = function (effect, scene) {
  38788. if (scene._forcedViewPosition) {
  38789. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38790. return;
  38791. }
  38792. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38793. };
  38794. /**
  38795. * Helps preparing the defines values about the UVs in used in the effect.
  38796. * UVs are shared as much as we can accross chanels in the shaders.
  38797. * @param texture The texture we are preparing the UVs for
  38798. * @param defines The defines to update
  38799. * @param key The chanel key "diffuse", "specular"... used in the shader
  38800. */
  38801. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38802. defines._needUVs = true;
  38803. defines[key] = true;
  38804. if (texture.getTextureMatrix().isIdentity(true)) {
  38805. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38806. if (texture.coordinatesIndex === 0) {
  38807. defines["MAINUV1"] = true;
  38808. }
  38809. else {
  38810. defines["MAINUV2"] = true;
  38811. }
  38812. }
  38813. else {
  38814. defines[key + "DIRECTUV"] = 0;
  38815. }
  38816. };
  38817. /**
  38818. * Binds a texture matrix value to its corrsponding uniform
  38819. * @param texture The texture to bind the matrix for
  38820. * @param uniformBuffer The uniform buffer receivin the data
  38821. * @param key The chanel key "diffuse", "specular"... used in the shader
  38822. */
  38823. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38824. var matrix = texture.getTextureMatrix();
  38825. if (!matrix.isIdentity(true)) {
  38826. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38827. }
  38828. };
  38829. /**
  38830. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38831. * @param mesh defines the current mesh
  38832. * @param scene defines the current scene
  38833. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38834. * @param pointsCloud defines if point cloud rendering has to be turned on
  38835. * @param fogEnabled defines if fog has to be turned on
  38836. * @param alphaTest defines if alpha testing has to be turned on
  38837. * @param defines defines the current list of defines
  38838. */
  38839. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38840. if (defines._areMiscDirty) {
  38841. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38842. defines["POINTSIZE"] = pointsCloud;
  38843. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38844. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38845. defines["ALPHATEST"] = alphaTest;
  38846. }
  38847. };
  38848. /**
  38849. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38850. * @param scene defines the current scene
  38851. * @param engine defines the current engine
  38852. * @param defines specifies the list of active defines
  38853. * @param useInstances defines if instances have to be turned on
  38854. * @param useClipPlane defines if clip plane have to be turned on
  38855. */
  38856. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38857. if (useClipPlane === void 0) { useClipPlane = null; }
  38858. var changed = false;
  38859. if (useClipPlane == null) {
  38860. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38861. }
  38862. if (defines["CLIPPLANE"] !== useClipPlane) {
  38863. defines["CLIPPLANE"] = useClipPlane;
  38864. changed = true;
  38865. }
  38866. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38867. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38868. changed = true;
  38869. }
  38870. if (defines["INSTANCES"] !== useInstances) {
  38871. defines["INSTANCES"] = useInstances;
  38872. changed = true;
  38873. }
  38874. if (changed) {
  38875. defines.markAsUnprocessed();
  38876. }
  38877. };
  38878. /**
  38879. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38880. * @param mesh The mesh containing the geometry data we will draw
  38881. * @param defines The defines to update
  38882. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38883. * @param useBones Precise whether bones should be used or not (override mesh info)
  38884. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38885. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38886. * @returns false if defines are considered not dirty and have not been checked
  38887. */
  38888. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38889. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38890. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38891. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38892. return false;
  38893. }
  38894. defines._normals = defines._needNormals;
  38895. defines._uvs = defines._needUVs;
  38896. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38897. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38898. defines["TANGENT"] = true;
  38899. }
  38900. if (defines._needUVs) {
  38901. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38902. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38903. }
  38904. else {
  38905. defines["UV1"] = false;
  38906. defines["UV2"] = false;
  38907. }
  38908. if (useVertexColor) {
  38909. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38910. defines["VERTEXCOLOR"] = hasVertexColors;
  38911. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38912. }
  38913. if (useBones) {
  38914. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38915. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38916. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38917. }
  38918. else {
  38919. defines["NUM_BONE_INFLUENCERS"] = 0;
  38920. defines["BonesPerMesh"] = 0;
  38921. }
  38922. }
  38923. if (useMorphTargets) {
  38924. var manager = mesh.morphTargetManager;
  38925. if (manager) {
  38926. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38927. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38928. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38929. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38930. }
  38931. else {
  38932. defines["MORPHTARGETS_TANGENT"] = false;
  38933. defines["MORPHTARGETS_NORMAL"] = false;
  38934. defines["MORPHTARGETS"] = false;
  38935. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38936. }
  38937. }
  38938. return true;
  38939. };
  38940. /**
  38941. * Prepares the defines related to the light information passed in parameter
  38942. * @param scene The scene we are intending to draw
  38943. * @param mesh The mesh the effect is compiling for
  38944. * @param defines The defines to update
  38945. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38946. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38947. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38948. * @returns true if normals will be required for the rest of the effect
  38949. */
  38950. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38951. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38952. if (disableLighting === void 0) { disableLighting = false; }
  38953. if (!defines._areLightsDirty) {
  38954. return defines._needNormals;
  38955. }
  38956. var lightIndex = 0;
  38957. var needNormals = false;
  38958. var needRebuild = false;
  38959. var lightmapMode = false;
  38960. var shadowEnabled = false;
  38961. var specularEnabled = false;
  38962. if (scene.lightsEnabled && !disableLighting) {
  38963. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38964. var light = _a[_i];
  38965. needNormals = true;
  38966. if (defines["LIGHT" + lightIndex] === undefined) {
  38967. needRebuild = true;
  38968. }
  38969. defines["LIGHT" + lightIndex] = true;
  38970. defines["SPOTLIGHT" + lightIndex] = false;
  38971. defines["HEMILIGHT" + lightIndex] = false;
  38972. defines["POINTLIGHT" + lightIndex] = false;
  38973. defines["DIRLIGHT" + lightIndex] = false;
  38974. var type;
  38975. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38976. type = "SPOTLIGHT" + lightIndex;
  38977. var spotLight = light;
  38978. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38979. }
  38980. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38981. type = "HEMILIGHT" + lightIndex;
  38982. }
  38983. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38984. type = "POINTLIGHT" + lightIndex;
  38985. }
  38986. else {
  38987. type = "DIRLIGHT" + lightIndex;
  38988. }
  38989. defines[type] = true;
  38990. // Specular
  38991. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38992. specularEnabled = true;
  38993. }
  38994. // Shadows
  38995. defines["SHADOW" + lightIndex] = false;
  38996. defines["SHADOWPCF" + lightIndex] = false;
  38997. defines["SHADOWPCSS" + lightIndex] = false;
  38998. defines["SHADOWPOISSON" + lightIndex] = false;
  38999. defines["SHADOWESM" + lightIndex] = false;
  39000. defines["SHADOWCUBE" + lightIndex] = false;
  39001. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39002. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39003. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39004. var shadowGenerator = light.getShadowGenerator();
  39005. if (shadowGenerator) {
  39006. shadowEnabled = true;
  39007. shadowGenerator.prepareDefines(defines, lightIndex);
  39008. }
  39009. }
  39010. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39011. lightmapMode = true;
  39012. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39013. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39014. }
  39015. else {
  39016. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39017. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39018. }
  39019. lightIndex++;
  39020. if (lightIndex === maxSimultaneousLights)
  39021. break;
  39022. }
  39023. }
  39024. defines["SPECULARTERM"] = specularEnabled;
  39025. defines["SHADOWS"] = shadowEnabled;
  39026. // Resetting all other lights if any
  39027. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39028. if (defines["LIGHT" + index] !== undefined) {
  39029. defines["LIGHT" + index] = false;
  39030. defines["HEMILIGHT" + lightIndex] = false;
  39031. defines["POINTLIGHT" + lightIndex] = false;
  39032. defines["DIRLIGHT" + lightIndex] = false;
  39033. defines["SPOTLIGHT" + lightIndex] = false;
  39034. defines["SHADOW" + lightIndex] = false;
  39035. }
  39036. }
  39037. var caps = scene.getEngine().getCaps();
  39038. if (defines["SHADOWFLOAT"] === undefined) {
  39039. needRebuild = true;
  39040. }
  39041. defines["SHADOWFLOAT"] = shadowEnabled &&
  39042. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39043. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39044. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39045. if (needRebuild) {
  39046. defines.rebuild();
  39047. }
  39048. return needNormals;
  39049. };
  39050. /**
  39051. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39052. * that won t be acctive due to defines being turned off.
  39053. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39054. * @param samplersList The samplers list
  39055. * @param defines The defines helping in the list generation
  39056. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39057. */
  39058. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39059. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39060. var uniformsList;
  39061. var uniformBuffersList = null;
  39062. if (uniformsListOrOptions.uniformsNames) {
  39063. var options = uniformsListOrOptions;
  39064. uniformsList = options.uniformsNames;
  39065. uniformBuffersList = options.uniformBuffersNames;
  39066. samplersList = options.samplers;
  39067. defines = options.defines;
  39068. maxSimultaneousLights = options.maxSimultaneousLights;
  39069. }
  39070. else {
  39071. uniformsList = uniformsListOrOptions;
  39072. if (!samplersList) {
  39073. samplersList = [];
  39074. }
  39075. }
  39076. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39077. if (!defines["LIGHT" + lightIndex]) {
  39078. break;
  39079. }
  39080. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39081. if (uniformBuffersList) {
  39082. uniformBuffersList.push("Light" + lightIndex);
  39083. }
  39084. samplersList.push("shadowSampler" + lightIndex);
  39085. samplersList.push("depthSampler" + lightIndex);
  39086. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39087. samplersList.push("projectionLightSampler" + lightIndex);
  39088. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39089. }
  39090. }
  39091. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39092. uniformsList.push("morphTargetInfluences");
  39093. }
  39094. };
  39095. /**
  39096. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39097. * @param defines The defines to update while falling back
  39098. * @param fallbacks The authorized effect fallbacks
  39099. * @param maxSimultaneousLights The maximum number of lights allowed
  39100. * @param rank the current rank of the Effect
  39101. * @returns The newly affected rank
  39102. */
  39103. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39104. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39105. if (rank === void 0) { rank = 0; }
  39106. var lightFallbackRank = 0;
  39107. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39108. if (!defines["LIGHT" + lightIndex]) {
  39109. break;
  39110. }
  39111. if (lightIndex > 0) {
  39112. lightFallbackRank = rank + lightIndex;
  39113. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39114. }
  39115. if (!defines["SHADOWS"]) {
  39116. if (defines["SHADOW" + lightIndex]) {
  39117. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39118. }
  39119. if (defines["SHADOWPCF" + lightIndex]) {
  39120. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39121. }
  39122. if (defines["SHADOWPCSS" + lightIndex]) {
  39123. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39124. }
  39125. if (defines["SHADOWPOISSON" + lightIndex]) {
  39126. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39127. }
  39128. if (defines["SHADOWESM" + lightIndex]) {
  39129. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39130. }
  39131. }
  39132. }
  39133. return lightFallbackRank++;
  39134. };
  39135. /**
  39136. * Prepares the list of attributes required for morph targets according to the effect defines.
  39137. * @param attribs The current list of supported attribs
  39138. * @param mesh The mesh to prepare the morph targets attributes for
  39139. * @param defines The current Defines of the effect
  39140. */
  39141. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39142. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39143. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39144. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39145. var manager = mesh.morphTargetManager;
  39146. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39147. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39148. for (var index = 0; index < influencers; index++) {
  39149. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39150. if (normal) {
  39151. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39152. }
  39153. if (tangent) {
  39154. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39155. }
  39156. if (attribs.length > maxAttributesCount) {
  39157. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39158. }
  39159. }
  39160. }
  39161. };
  39162. /**
  39163. * Prepares the list of attributes required for bones according to the effect defines.
  39164. * @param attribs The current list of supported attribs
  39165. * @param mesh The mesh to prepare the bones attributes for
  39166. * @param defines The current Defines of the effect
  39167. * @param fallbacks The current efffect fallback strategy
  39168. */
  39169. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39170. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39171. fallbacks.addCPUSkinningFallback(0, mesh);
  39172. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39173. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39174. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39175. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39176. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39177. }
  39178. }
  39179. };
  39180. /**
  39181. * Prepares the list of attributes required for instances according to the effect defines.
  39182. * @param attribs The current list of supported attribs
  39183. * @param defines The current Defines of the effect
  39184. */
  39185. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39186. if (defines["INSTANCES"]) {
  39187. attribs.push("world0");
  39188. attribs.push("world1");
  39189. attribs.push("world2");
  39190. attribs.push("world3");
  39191. }
  39192. };
  39193. /**
  39194. * Binds the light shadow information to the effect for the given mesh.
  39195. * @param light The light containing the generator
  39196. * @param scene The scene the lights belongs to
  39197. * @param mesh The mesh we are binding the information to render
  39198. * @param lightIndex The light index in the effect used to render the mesh
  39199. * @param effect The effect we are binding the data to
  39200. */
  39201. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39202. if (light.shadowEnabled && mesh.receiveShadows) {
  39203. var shadowGenerator = light.getShadowGenerator();
  39204. if (shadowGenerator) {
  39205. shadowGenerator.bindShadowLight(lightIndex, effect);
  39206. }
  39207. }
  39208. };
  39209. /**
  39210. * Binds the light information to the effect.
  39211. * @param light The light containing the generator
  39212. * @param effect The effect we are binding the data to
  39213. * @param lightIndex The light index in the effect used to render
  39214. */
  39215. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39216. light.transferToEffect(effect, lightIndex + "");
  39217. };
  39218. /**
  39219. * Binds the lights information from the scene to the effect for the given mesh.
  39220. * @param scene The scene the lights belongs to
  39221. * @param mesh The mesh we are binding the information to render
  39222. * @param effect The effect we are binding the data to
  39223. * @param defines The generated defines for the effect
  39224. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39225. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39226. */
  39227. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39228. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39229. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39230. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39231. for (var i = 0; i < len; i++) {
  39232. var light = mesh._lightSources[i];
  39233. var iAsString = i.toString();
  39234. var scaledIntensity = light.getScaledIntensity();
  39235. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39236. MaterialHelper.BindLightProperties(light, effect, i);
  39237. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39238. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39239. if (defines["SPECULARTERM"]) {
  39240. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39241. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39242. }
  39243. // Shadows
  39244. if (scene.shadowsEnabled) {
  39245. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39246. }
  39247. light._uniformBuffer.update();
  39248. }
  39249. };
  39250. /**
  39251. * Binds the fog information from the scene to the effect for the given mesh.
  39252. * @param scene The scene the lights belongs to
  39253. * @param mesh The mesh we are binding the information to render
  39254. * @param effect The effect we are binding the data to
  39255. */
  39256. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39257. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39258. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39259. effect.setColor3("vFogColor", scene.fogColor);
  39260. }
  39261. };
  39262. /**
  39263. * Binds the bones information from the mesh to the effect.
  39264. * @param mesh The mesh we are binding the information to render
  39265. * @param effect The effect we are binding the data to
  39266. */
  39267. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39268. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39269. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39270. if (matrices && effect) {
  39271. effect.setMatrices("mBones", matrices);
  39272. }
  39273. }
  39274. };
  39275. /**
  39276. * Binds the morph targets information from the mesh to the effect.
  39277. * @param abstractMesh The mesh we are binding the information to render
  39278. * @param effect The effect we are binding the data to
  39279. */
  39280. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39281. var manager = abstractMesh.morphTargetManager;
  39282. if (!abstractMesh || !manager) {
  39283. return;
  39284. }
  39285. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39286. };
  39287. /**
  39288. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39289. * @param defines The generated defines used in the effect
  39290. * @param effect The effect we are binding the data to
  39291. * @param scene The scene we are willing to render with logarithmic scale for
  39292. */
  39293. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39294. if (defines["LOGARITHMICDEPTH"]) {
  39295. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39296. }
  39297. };
  39298. /**
  39299. * Binds the clip plane information from the scene to the effect.
  39300. * @param scene The scene the clip plane information are extracted from
  39301. * @param effect The effect we are binding the data to
  39302. */
  39303. MaterialHelper.BindClipPlane = function (effect, scene) {
  39304. if (scene.clipPlane) {
  39305. var clipPlane = scene.clipPlane;
  39306. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39307. }
  39308. };
  39309. return MaterialHelper;
  39310. }());
  39311. BABYLON.MaterialHelper = MaterialHelper;
  39312. })(BABYLON || (BABYLON = {}));
  39313. //# sourceMappingURL=babylon.materialHelper.js.map
  39314. "use strict";
  39315. var BABYLON;
  39316. (function (BABYLON) {
  39317. var PushMaterial = /** @class */ (function (_super) {
  39318. __extends(PushMaterial, _super);
  39319. function PushMaterial(name, scene) {
  39320. var _this = _super.call(this, name, scene) || this;
  39321. _this._normalMatrix = new BABYLON.Matrix();
  39322. _this.storeEffectOnSubMeshes = true;
  39323. return _this;
  39324. }
  39325. PushMaterial.prototype.getEffect = function () {
  39326. return this._activeEffect;
  39327. };
  39328. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39329. if (!mesh) {
  39330. return false;
  39331. }
  39332. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39333. return true;
  39334. }
  39335. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39336. };
  39337. /**
  39338. * Binds the given world matrix to the active effect
  39339. *
  39340. * @param world the matrix to bind
  39341. */
  39342. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39343. this._activeEffect.setMatrix("world", world);
  39344. };
  39345. /**
  39346. * Binds the given normal matrix to the active effect
  39347. *
  39348. * @param normalMatrix the matrix to bind
  39349. */
  39350. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39351. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39352. };
  39353. PushMaterial.prototype.bind = function (world, mesh) {
  39354. if (!mesh) {
  39355. return;
  39356. }
  39357. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39358. };
  39359. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39360. if (effect === void 0) { effect = null; }
  39361. _super.prototype._afterBind.call(this, mesh);
  39362. this.getScene()._cachedEffect = effect;
  39363. };
  39364. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39365. if (visibility === void 0) { visibility = 1; }
  39366. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39367. };
  39368. return PushMaterial;
  39369. }(BABYLON.Material));
  39370. BABYLON.PushMaterial = PushMaterial;
  39371. })(BABYLON || (BABYLON = {}));
  39372. //# sourceMappingURL=babylon.pushMaterial.js.map
  39373. "use strict";
  39374. var BABYLON;
  39375. (function (BABYLON) {
  39376. /** @ignore */
  39377. var StandardMaterialDefines = /** @class */ (function (_super) {
  39378. __extends(StandardMaterialDefines, _super);
  39379. function StandardMaterialDefines() {
  39380. var _this = _super.call(this) || this;
  39381. _this.MAINUV1 = false;
  39382. _this.MAINUV2 = false;
  39383. _this.DIFFUSE = false;
  39384. _this.DIFFUSEDIRECTUV = 0;
  39385. _this.AMBIENT = false;
  39386. _this.AMBIENTDIRECTUV = 0;
  39387. _this.OPACITY = false;
  39388. _this.OPACITYDIRECTUV = 0;
  39389. _this.OPACITYRGB = false;
  39390. _this.REFLECTION = false;
  39391. _this.EMISSIVE = false;
  39392. _this.EMISSIVEDIRECTUV = 0;
  39393. _this.SPECULAR = false;
  39394. _this.SPECULARDIRECTUV = 0;
  39395. _this.BUMP = false;
  39396. _this.BUMPDIRECTUV = 0;
  39397. _this.PARALLAX = false;
  39398. _this.PARALLAXOCCLUSION = false;
  39399. _this.SPECULAROVERALPHA = false;
  39400. _this.CLIPPLANE = false;
  39401. _this.ALPHATEST = false;
  39402. _this.DEPTHPREPASS = false;
  39403. _this.ALPHAFROMDIFFUSE = false;
  39404. _this.POINTSIZE = false;
  39405. _this.FOG = false;
  39406. _this.SPECULARTERM = false;
  39407. _this.DIFFUSEFRESNEL = false;
  39408. _this.OPACITYFRESNEL = false;
  39409. _this.REFLECTIONFRESNEL = false;
  39410. _this.REFRACTIONFRESNEL = false;
  39411. _this.EMISSIVEFRESNEL = false;
  39412. _this.FRESNEL = false;
  39413. _this.NORMAL = false;
  39414. _this.UV1 = false;
  39415. _this.UV2 = false;
  39416. _this.VERTEXCOLOR = false;
  39417. _this.VERTEXALPHA = false;
  39418. _this.NUM_BONE_INFLUENCERS = 0;
  39419. _this.BonesPerMesh = 0;
  39420. _this.INSTANCES = false;
  39421. _this.GLOSSINESS = false;
  39422. _this.ROUGHNESS = false;
  39423. _this.EMISSIVEASILLUMINATION = false;
  39424. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39425. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39426. _this.LIGHTMAP = false;
  39427. _this.LIGHTMAPDIRECTUV = 0;
  39428. _this.OBJECTSPACE_NORMALMAP = false;
  39429. _this.USELIGHTMAPASSHADOWMAP = false;
  39430. _this.REFLECTIONMAP_3D = false;
  39431. _this.REFLECTIONMAP_SPHERICAL = false;
  39432. _this.REFLECTIONMAP_PLANAR = false;
  39433. _this.REFLECTIONMAP_CUBIC = false;
  39434. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39435. _this.REFLECTIONMAP_PROJECTION = false;
  39436. _this.REFLECTIONMAP_SKYBOX = false;
  39437. _this.REFLECTIONMAP_EXPLICIT = false;
  39438. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39439. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39440. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39441. _this.INVERTCUBICMAP = false;
  39442. _this.LOGARITHMICDEPTH = false;
  39443. _this.REFRACTION = false;
  39444. _this.REFRACTIONMAP_3D = false;
  39445. _this.REFLECTIONOVERALPHA = false;
  39446. _this.TWOSIDEDLIGHTING = false;
  39447. _this.SHADOWFLOAT = false;
  39448. _this.MORPHTARGETS = false;
  39449. _this.MORPHTARGETS_NORMAL = false;
  39450. _this.MORPHTARGETS_TANGENT = false;
  39451. _this.NUM_MORPH_INFLUENCERS = 0;
  39452. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39453. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39454. _this.IMAGEPROCESSING = false;
  39455. _this.VIGNETTE = false;
  39456. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39457. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39458. _this.TONEMAPPING = false;
  39459. _this.CONTRAST = false;
  39460. _this.COLORCURVES = false;
  39461. _this.COLORGRADING = false;
  39462. _this.COLORGRADING3D = false;
  39463. _this.SAMPLER3DGREENDEPTH = false;
  39464. _this.SAMPLER3DBGRMAP = false;
  39465. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39466. _this.EXPOSURE = false;
  39467. _this.GRAIN = false;
  39468. _this.rebuild();
  39469. return _this;
  39470. }
  39471. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39472. var modes = [
  39473. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39474. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39475. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39476. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39477. ];
  39478. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39479. var mode = modes_1[_i];
  39480. this[mode] = (mode === modeToEnable);
  39481. }
  39482. };
  39483. return StandardMaterialDefines;
  39484. }(BABYLON.MaterialDefines));
  39485. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39486. var StandardMaterial = /** @class */ (function (_super) {
  39487. __extends(StandardMaterial, _super);
  39488. function StandardMaterial(name, scene) {
  39489. var _this = _super.call(this, name, scene) || this;
  39490. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39491. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39492. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39493. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39494. _this.specularPower = 64;
  39495. _this._useAlphaFromDiffuseTexture = false;
  39496. _this._useEmissiveAsIllumination = false;
  39497. _this._linkEmissiveWithDiffuse = false;
  39498. _this._useSpecularOverAlpha = false;
  39499. _this._useReflectionOverAlpha = false;
  39500. _this._disableLighting = false;
  39501. _this._useObjectSpaceNormalMap = false;
  39502. _this._useParallax = false;
  39503. _this._useParallaxOcclusion = false;
  39504. _this.parallaxScaleBias = 0.05;
  39505. _this._roughness = 0;
  39506. _this.indexOfRefraction = 0.98;
  39507. _this.invertRefractionY = true;
  39508. _this._useLightmapAsShadowmap = false;
  39509. _this._useReflectionFresnelFromSpecular = false;
  39510. _this._useGlossinessFromSpecularMapAlpha = false;
  39511. _this._maxSimultaneousLights = 4;
  39512. /**
  39513. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39514. */
  39515. _this._invertNormalMapX = false;
  39516. /**
  39517. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39518. */
  39519. _this._invertNormalMapY = false;
  39520. /**
  39521. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39522. */
  39523. _this._twoSidedLighting = false;
  39524. _this._renderTargets = new BABYLON.SmartArray(16);
  39525. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39526. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39527. // Setup the default processing configuration to the scene.
  39528. _this._attachImageProcessingConfiguration(null);
  39529. _this.getRenderTargetTextures = function () {
  39530. _this._renderTargets.reset();
  39531. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39532. _this._renderTargets.push(_this._reflectionTexture);
  39533. }
  39534. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39535. _this._renderTargets.push(_this._refractionTexture);
  39536. }
  39537. return _this._renderTargets;
  39538. };
  39539. return _this;
  39540. }
  39541. ;
  39542. ;
  39543. ;
  39544. ;
  39545. ;
  39546. ;
  39547. ;
  39548. ;
  39549. ;
  39550. ;
  39551. ;
  39552. ;
  39553. ;
  39554. ;
  39555. ;
  39556. ;
  39557. ;
  39558. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39559. /**
  39560. * Gets the image processing configuration used either in this material.
  39561. */
  39562. get: function () {
  39563. return this._imageProcessingConfiguration;
  39564. },
  39565. /**
  39566. * Sets the Default image processing configuration used either in the this material.
  39567. *
  39568. * If sets to null, the scene one is in use.
  39569. */
  39570. set: function (value) {
  39571. this._attachImageProcessingConfiguration(value);
  39572. // Ensure the effect will be rebuilt.
  39573. this._markAllSubMeshesAsTexturesDirty();
  39574. },
  39575. enumerable: true,
  39576. configurable: true
  39577. });
  39578. /**
  39579. * Attaches a new image processing configuration to the Standard Material.
  39580. * @param configuration
  39581. */
  39582. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39583. var _this = this;
  39584. if (configuration === this._imageProcessingConfiguration) {
  39585. return;
  39586. }
  39587. // Detaches observer.
  39588. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39589. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39590. }
  39591. // Pick the scene configuration if needed.
  39592. if (!configuration) {
  39593. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39594. }
  39595. else {
  39596. this._imageProcessingConfiguration = configuration;
  39597. }
  39598. // Attaches observer.
  39599. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39600. _this._markAllSubMeshesAsImageProcessingDirty();
  39601. });
  39602. };
  39603. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39604. /**
  39605. * Gets wether the color curves effect is enabled.
  39606. */
  39607. get: function () {
  39608. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39609. },
  39610. /**
  39611. * Sets wether the color curves effect is enabled.
  39612. */
  39613. set: function (value) {
  39614. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39615. },
  39616. enumerable: true,
  39617. configurable: true
  39618. });
  39619. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39620. /**
  39621. * Gets wether the color grading effect is enabled.
  39622. */
  39623. get: function () {
  39624. return this.imageProcessingConfiguration.colorGradingEnabled;
  39625. },
  39626. /**
  39627. * Gets wether the color grading effect is enabled.
  39628. */
  39629. set: function (value) {
  39630. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39631. },
  39632. enumerable: true,
  39633. configurable: true
  39634. });
  39635. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39636. /**
  39637. * Gets wether tonemapping is enabled or not.
  39638. */
  39639. get: function () {
  39640. return this._imageProcessingConfiguration.toneMappingEnabled;
  39641. },
  39642. /**
  39643. * Sets wether tonemapping is enabled or not
  39644. */
  39645. set: function (value) {
  39646. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39647. },
  39648. enumerable: true,
  39649. configurable: true
  39650. });
  39651. ;
  39652. ;
  39653. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39654. /**
  39655. * The camera exposure used on this material.
  39656. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39657. * This corresponds to a photographic exposure.
  39658. */
  39659. get: function () {
  39660. return this._imageProcessingConfiguration.exposure;
  39661. },
  39662. /**
  39663. * The camera exposure used on this material.
  39664. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39665. * This corresponds to a photographic exposure.
  39666. */
  39667. set: function (value) {
  39668. this._imageProcessingConfiguration.exposure = value;
  39669. },
  39670. enumerable: true,
  39671. configurable: true
  39672. });
  39673. ;
  39674. ;
  39675. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39676. /**
  39677. * Gets The camera contrast used on this material.
  39678. */
  39679. get: function () {
  39680. return this._imageProcessingConfiguration.contrast;
  39681. },
  39682. /**
  39683. * Sets The camera contrast used on this material.
  39684. */
  39685. set: function (value) {
  39686. this._imageProcessingConfiguration.contrast = value;
  39687. },
  39688. enumerable: true,
  39689. configurable: true
  39690. });
  39691. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39692. /**
  39693. * Gets the Color Grading 2D Lookup Texture.
  39694. */
  39695. get: function () {
  39696. return this._imageProcessingConfiguration.colorGradingTexture;
  39697. },
  39698. /**
  39699. * Sets the Color Grading 2D Lookup Texture.
  39700. */
  39701. set: function (value) {
  39702. this._imageProcessingConfiguration.colorGradingTexture = value;
  39703. },
  39704. enumerable: true,
  39705. configurable: true
  39706. });
  39707. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39708. /**
  39709. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39710. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39711. * 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;
  39712. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39713. */
  39714. get: function () {
  39715. return this._imageProcessingConfiguration.colorCurves;
  39716. },
  39717. /**
  39718. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39719. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39720. * 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;
  39721. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39722. */
  39723. set: function (value) {
  39724. this._imageProcessingConfiguration.colorCurves = value;
  39725. },
  39726. enumerable: true,
  39727. configurable: true
  39728. });
  39729. StandardMaterial.prototype.getClassName = function () {
  39730. return "StandardMaterial";
  39731. };
  39732. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39733. get: function () {
  39734. return this._useLogarithmicDepth;
  39735. },
  39736. set: function (value) {
  39737. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39738. this._markAllSubMeshesAsMiscDirty();
  39739. },
  39740. enumerable: true,
  39741. configurable: true
  39742. });
  39743. StandardMaterial.prototype.needAlphaBlending = function () {
  39744. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39745. };
  39746. StandardMaterial.prototype.needAlphaTesting = function () {
  39747. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39748. };
  39749. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39750. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39751. };
  39752. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39753. return this._diffuseTexture;
  39754. };
  39755. /**
  39756. * Child classes can use it to update shaders
  39757. */
  39758. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39759. if (useInstances === void 0) { useInstances = false; }
  39760. if (subMesh.effect && this.isFrozen) {
  39761. if (this._wasPreviouslyReady && subMesh.effect) {
  39762. return true;
  39763. }
  39764. }
  39765. if (!subMesh._materialDefines) {
  39766. subMesh._materialDefines = new StandardMaterialDefines();
  39767. }
  39768. var scene = this.getScene();
  39769. var defines = subMesh._materialDefines;
  39770. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39771. if (defines._renderId === scene.getRenderId()) {
  39772. return true;
  39773. }
  39774. }
  39775. var engine = scene.getEngine();
  39776. // Lights
  39777. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39778. // Textures
  39779. if (defines._areTexturesDirty) {
  39780. defines._needUVs = false;
  39781. defines.MAINUV1 = false;
  39782. defines.MAINUV2 = false;
  39783. if (scene.texturesEnabled) {
  39784. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39785. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39786. return false;
  39787. }
  39788. else {
  39789. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39790. }
  39791. }
  39792. else {
  39793. defines.DIFFUSE = false;
  39794. }
  39795. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39796. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39797. return false;
  39798. }
  39799. else {
  39800. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39801. }
  39802. }
  39803. else {
  39804. defines.AMBIENT = false;
  39805. }
  39806. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39807. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39808. return false;
  39809. }
  39810. else {
  39811. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39812. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39813. }
  39814. }
  39815. else {
  39816. defines.OPACITY = false;
  39817. }
  39818. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39819. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39820. return false;
  39821. }
  39822. else {
  39823. defines._needNormals = true;
  39824. defines.REFLECTION = true;
  39825. defines.ROUGHNESS = (this._roughness > 0);
  39826. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39827. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39828. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39829. switch (this._reflectionTexture.coordinatesMode) {
  39830. case BABYLON.Texture.CUBIC_MODE:
  39831. case BABYLON.Texture.INVCUBIC_MODE:
  39832. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39833. break;
  39834. case BABYLON.Texture.EXPLICIT_MODE:
  39835. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39836. break;
  39837. case BABYLON.Texture.PLANAR_MODE:
  39838. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39839. break;
  39840. case BABYLON.Texture.PROJECTION_MODE:
  39841. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39842. break;
  39843. case BABYLON.Texture.SKYBOX_MODE:
  39844. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39845. break;
  39846. case BABYLON.Texture.SPHERICAL_MODE:
  39847. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39848. break;
  39849. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39850. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39851. break;
  39852. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39853. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39854. break;
  39855. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39856. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39857. break;
  39858. }
  39859. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39860. }
  39861. }
  39862. else {
  39863. defines.REFLECTION = false;
  39864. }
  39865. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39866. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39867. return false;
  39868. }
  39869. else {
  39870. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39871. }
  39872. }
  39873. else {
  39874. defines.EMISSIVE = false;
  39875. }
  39876. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39877. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39878. return false;
  39879. }
  39880. else {
  39881. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39882. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39883. }
  39884. }
  39885. else {
  39886. defines.LIGHTMAP = false;
  39887. }
  39888. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39889. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39890. return false;
  39891. }
  39892. else {
  39893. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39894. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39895. }
  39896. }
  39897. else {
  39898. defines.SPECULAR = false;
  39899. }
  39900. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39901. // Bump texure can not be not blocking.
  39902. if (!this._bumpTexture.isReady()) {
  39903. return false;
  39904. }
  39905. else {
  39906. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39907. defines.PARALLAX = this._useParallax;
  39908. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39909. }
  39910. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39911. }
  39912. else {
  39913. defines.BUMP = false;
  39914. }
  39915. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39916. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39917. return false;
  39918. }
  39919. else {
  39920. defines._needUVs = true;
  39921. defines.REFRACTION = true;
  39922. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39923. }
  39924. }
  39925. else {
  39926. defines.REFRACTION = false;
  39927. }
  39928. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39929. }
  39930. else {
  39931. defines.DIFFUSE = false;
  39932. defines.AMBIENT = false;
  39933. defines.OPACITY = false;
  39934. defines.REFLECTION = false;
  39935. defines.EMISSIVE = false;
  39936. defines.LIGHTMAP = false;
  39937. defines.BUMP = false;
  39938. defines.REFRACTION = false;
  39939. }
  39940. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39941. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39942. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39943. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39944. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39945. }
  39946. if (defines._areImageProcessingDirty) {
  39947. if (!this._imageProcessingConfiguration.isReady()) {
  39948. return false;
  39949. }
  39950. this._imageProcessingConfiguration.prepareDefines(defines);
  39951. }
  39952. if (defines._areFresnelDirty) {
  39953. if (StandardMaterial.FresnelEnabled) {
  39954. // Fresnel
  39955. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39956. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39957. this._reflectionFresnelParameters) {
  39958. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39959. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39960. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39961. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39962. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39963. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39964. defines._needNormals = true;
  39965. defines.FRESNEL = true;
  39966. }
  39967. }
  39968. else {
  39969. defines.FRESNEL = false;
  39970. }
  39971. }
  39972. // Misc.
  39973. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39974. // Attribs
  39975. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39976. // Values that need to be evaluated on every frame
  39977. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39978. // Get correct effect
  39979. if (defines.isDirty) {
  39980. defines.markAsProcessed();
  39981. scene.resetCachedMaterial();
  39982. // Fallbacks
  39983. var fallbacks = new BABYLON.EffectFallbacks();
  39984. if (defines.REFLECTION) {
  39985. fallbacks.addFallback(0, "REFLECTION");
  39986. }
  39987. if (defines.SPECULAR) {
  39988. fallbacks.addFallback(0, "SPECULAR");
  39989. }
  39990. if (defines.BUMP) {
  39991. fallbacks.addFallback(0, "BUMP");
  39992. }
  39993. if (defines.PARALLAX) {
  39994. fallbacks.addFallback(1, "PARALLAX");
  39995. }
  39996. if (defines.PARALLAXOCCLUSION) {
  39997. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39998. }
  39999. if (defines.SPECULAROVERALPHA) {
  40000. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40001. }
  40002. if (defines.FOG) {
  40003. fallbacks.addFallback(1, "FOG");
  40004. }
  40005. if (defines.POINTSIZE) {
  40006. fallbacks.addFallback(0, "POINTSIZE");
  40007. }
  40008. if (defines.LOGARITHMICDEPTH) {
  40009. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40010. }
  40011. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40012. if (defines.SPECULARTERM) {
  40013. fallbacks.addFallback(0, "SPECULARTERM");
  40014. }
  40015. if (defines.DIFFUSEFRESNEL) {
  40016. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40017. }
  40018. if (defines.OPACITYFRESNEL) {
  40019. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40020. }
  40021. if (defines.REFLECTIONFRESNEL) {
  40022. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40023. }
  40024. if (defines.EMISSIVEFRESNEL) {
  40025. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40026. }
  40027. if (defines.FRESNEL) {
  40028. fallbacks.addFallback(4, "FRESNEL");
  40029. }
  40030. //Attributes
  40031. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40032. if (defines.NORMAL) {
  40033. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40034. }
  40035. if (defines.UV1) {
  40036. attribs.push(BABYLON.VertexBuffer.UVKind);
  40037. }
  40038. if (defines.UV2) {
  40039. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40040. }
  40041. if (defines.VERTEXCOLOR) {
  40042. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40043. }
  40044. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40045. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40046. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40047. var shaderName = "default";
  40048. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40049. "vFogInfos", "vFogColor", "pointSize",
  40050. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40051. "mBones",
  40052. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40053. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40054. "vReflectionPosition", "vReflectionSize",
  40055. "logarithmicDepthConstant", "vTangentSpaceParams"
  40056. ];
  40057. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40058. var uniformBuffers = ["Material", "Scene"];
  40059. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40060. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40061. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40062. uniformsNames: uniforms,
  40063. uniformBuffersNames: uniformBuffers,
  40064. samplers: samplers,
  40065. defines: defines,
  40066. maxSimultaneousLights: this._maxSimultaneousLights
  40067. });
  40068. if (this.customShaderNameResolve) {
  40069. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40070. }
  40071. var join = defines.toString();
  40072. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40073. attributes: attribs,
  40074. uniformsNames: uniforms,
  40075. uniformBuffersNames: uniformBuffers,
  40076. samplers: samplers,
  40077. defines: join,
  40078. fallbacks: fallbacks,
  40079. onCompiled: this.onCompiled,
  40080. onError: this.onError,
  40081. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40082. }, engine), defines);
  40083. this.buildUniformLayout();
  40084. }
  40085. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40086. return false;
  40087. }
  40088. defines._renderId = scene.getRenderId();
  40089. this._wasPreviouslyReady = true;
  40090. return true;
  40091. };
  40092. StandardMaterial.prototype.buildUniformLayout = function () {
  40093. // Order is important !
  40094. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40095. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40096. this._uniformBuffer.addUniform("opacityParts", 4);
  40097. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40098. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40099. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40100. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40101. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40102. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40103. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40104. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40105. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40106. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40107. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40108. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40109. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40110. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40111. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40112. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40113. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40114. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40115. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40116. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40117. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40118. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40119. this._uniformBuffer.addUniform("specularMatrix", 16);
  40120. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40121. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40122. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40123. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40124. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40125. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40126. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40127. this._uniformBuffer.addUniform("pointSize", 1);
  40128. this._uniformBuffer.create();
  40129. };
  40130. StandardMaterial.prototype.unbind = function () {
  40131. if (this._activeEffect) {
  40132. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40133. this._activeEffect.setTexture("reflection2DSampler", null);
  40134. }
  40135. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40136. this._activeEffect.setTexture("refraction2DSampler", null);
  40137. }
  40138. }
  40139. _super.prototype.unbind.call(this);
  40140. };
  40141. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40142. var scene = this.getScene();
  40143. var defines = subMesh._materialDefines;
  40144. if (!defines) {
  40145. return;
  40146. }
  40147. var effect = subMesh.effect;
  40148. if (!effect) {
  40149. return;
  40150. }
  40151. this._activeEffect = effect;
  40152. // Matrices
  40153. this.bindOnlyWorldMatrix(world);
  40154. // Normal Matrix
  40155. if (defines.OBJECTSPACE_NORMALMAP) {
  40156. world.toNormalMatrix(this._normalMatrix);
  40157. this.bindOnlyNormalMatrix(this._normalMatrix);
  40158. }
  40159. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40160. // Bones
  40161. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40162. if (mustRebind) {
  40163. this._uniformBuffer.bindToEffect(effect, "Material");
  40164. this.bindViewProjection(effect);
  40165. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40166. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40167. // Fresnel
  40168. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40169. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40170. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40171. }
  40172. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40173. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40174. }
  40175. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40176. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40177. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40178. }
  40179. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40180. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40181. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40182. }
  40183. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40184. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40185. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40186. }
  40187. }
  40188. // Textures
  40189. if (scene.texturesEnabled) {
  40190. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40191. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40192. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40193. }
  40194. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40195. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40196. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40197. }
  40198. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40199. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40200. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40201. }
  40202. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40203. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40204. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40205. if (this._reflectionTexture.boundingBoxSize) {
  40206. var cubeTexture = this._reflectionTexture;
  40207. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40208. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40209. }
  40210. }
  40211. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40212. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40213. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40214. }
  40215. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40216. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40217. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40218. }
  40219. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40220. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40221. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40222. }
  40223. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40224. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40225. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40226. if (scene._mirroredCameraPosition) {
  40227. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40228. }
  40229. else {
  40230. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40231. }
  40232. }
  40233. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40234. var depth = 1.0;
  40235. if (!this._refractionTexture.isCube) {
  40236. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40237. if (this._refractionTexture.depth) {
  40238. depth = this._refractionTexture.depth;
  40239. }
  40240. }
  40241. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40242. }
  40243. }
  40244. // Point size
  40245. if (this.pointsCloud) {
  40246. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40247. }
  40248. if (defines.SPECULARTERM) {
  40249. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40250. }
  40251. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40252. // Diffuse
  40253. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40254. }
  40255. // Textures
  40256. if (scene.texturesEnabled) {
  40257. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40258. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40259. }
  40260. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40261. effect.setTexture("ambientSampler", this._ambientTexture);
  40262. }
  40263. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40264. effect.setTexture("opacitySampler", this._opacityTexture);
  40265. }
  40266. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40267. if (this._reflectionTexture.isCube) {
  40268. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40269. }
  40270. else {
  40271. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40272. }
  40273. }
  40274. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40275. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40276. }
  40277. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40278. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40279. }
  40280. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40281. effect.setTexture("specularSampler", this._specularTexture);
  40282. }
  40283. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40284. effect.setTexture("bumpSampler", this._bumpTexture);
  40285. }
  40286. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40287. var depth = 1.0;
  40288. if (this._refractionTexture.isCube) {
  40289. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40290. }
  40291. else {
  40292. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40293. }
  40294. }
  40295. }
  40296. // Clip plane
  40297. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40298. // Colors
  40299. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40300. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40301. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40302. }
  40303. if (mustRebind || !this.isFrozen) {
  40304. // Lights
  40305. if (scene.lightsEnabled && !this._disableLighting) {
  40306. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40307. }
  40308. // View
  40309. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40310. this.bindView(effect);
  40311. }
  40312. // Fog
  40313. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40314. // Morph targets
  40315. if (defines.NUM_MORPH_INFLUENCERS) {
  40316. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40317. }
  40318. // Log. depth
  40319. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40320. // image processing
  40321. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40322. this._imageProcessingConfiguration.bind(this._activeEffect);
  40323. }
  40324. }
  40325. this._uniformBuffer.update();
  40326. this._afterBind(mesh, this._activeEffect);
  40327. };
  40328. StandardMaterial.prototype.getAnimatables = function () {
  40329. var results = [];
  40330. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40331. results.push(this._diffuseTexture);
  40332. }
  40333. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40334. results.push(this._ambientTexture);
  40335. }
  40336. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40337. results.push(this._opacityTexture);
  40338. }
  40339. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40340. results.push(this._reflectionTexture);
  40341. }
  40342. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40343. results.push(this._emissiveTexture);
  40344. }
  40345. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40346. results.push(this._specularTexture);
  40347. }
  40348. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40349. results.push(this._bumpTexture);
  40350. }
  40351. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40352. results.push(this._lightmapTexture);
  40353. }
  40354. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40355. results.push(this._refractionTexture);
  40356. }
  40357. return results;
  40358. };
  40359. StandardMaterial.prototype.getActiveTextures = function () {
  40360. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40361. if (this._diffuseTexture) {
  40362. activeTextures.push(this._diffuseTexture);
  40363. }
  40364. if (this._ambientTexture) {
  40365. activeTextures.push(this._ambientTexture);
  40366. }
  40367. if (this._opacityTexture) {
  40368. activeTextures.push(this._opacityTexture);
  40369. }
  40370. if (this._reflectionTexture) {
  40371. activeTextures.push(this._reflectionTexture);
  40372. }
  40373. if (this._emissiveTexture) {
  40374. activeTextures.push(this._emissiveTexture);
  40375. }
  40376. if (this._specularTexture) {
  40377. activeTextures.push(this._specularTexture);
  40378. }
  40379. if (this._bumpTexture) {
  40380. activeTextures.push(this._bumpTexture);
  40381. }
  40382. if (this._lightmapTexture) {
  40383. activeTextures.push(this._lightmapTexture);
  40384. }
  40385. if (this._refractionTexture) {
  40386. activeTextures.push(this._refractionTexture);
  40387. }
  40388. return activeTextures;
  40389. };
  40390. StandardMaterial.prototype.hasTexture = function (texture) {
  40391. if (_super.prototype.hasTexture.call(this, texture)) {
  40392. return true;
  40393. }
  40394. if (this._diffuseTexture === texture) {
  40395. return true;
  40396. }
  40397. if (this._ambientTexture === texture) {
  40398. return true;
  40399. }
  40400. if (this._opacityTexture === texture) {
  40401. return true;
  40402. }
  40403. if (this._reflectionTexture === texture) {
  40404. return true;
  40405. }
  40406. if (this._emissiveTexture === texture) {
  40407. return true;
  40408. }
  40409. if (this._specularTexture === texture) {
  40410. return true;
  40411. }
  40412. if (this._bumpTexture === texture) {
  40413. return true;
  40414. }
  40415. if (this._lightmapTexture === texture) {
  40416. return true;
  40417. }
  40418. if (this._refractionTexture === texture) {
  40419. return true;
  40420. }
  40421. return false;
  40422. };
  40423. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40424. if (forceDisposeTextures) {
  40425. if (this._diffuseTexture) {
  40426. this._diffuseTexture.dispose();
  40427. }
  40428. if (this._ambientTexture) {
  40429. this._ambientTexture.dispose();
  40430. }
  40431. if (this._opacityTexture) {
  40432. this._opacityTexture.dispose();
  40433. }
  40434. if (this._reflectionTexture) {
  40435. this._reflectionTexture.dispose();
  40436. }
  40437. if (this._emissiveTexture) {
  40438. this._emissiveTexture.dispose();
  40439. }
  40440. if (this._specularTexture) {
  40441. this._specularTexture.dispose();
  40442. }
  40443. if (this._bumpTexture) {
  40444. this._bumpTexture.dispose();
  40445. }
  40446. if (this._lightmapTexture) {
  40447. this._lightmapTexture.dispose();
  40448. }
  40449. if (this._refractionTexture) {
  40450. this._refractionTexture.dispose();
  40451. }
  40452. }
  40453. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40454. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40455. }
  40456. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40457. };
  40458. StandardMaterial.prototype.clone = function (name) {
  40459. var _this = this;
  40460. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40461. result.name = name;
  40462. result.id = name;
  40463. return result;
  40464. };
  40465. StandardMaterial.prototype.serialize = function () {
  40466. return BABYLON.SerializationHelper.Serialize(this);
  40467. };
  40468. // Statics
  40469. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40470. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40471. };
  40472. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40473. get: function () {
  40474. return StandardMaterial._DiffuseTextureEnabled;
  40475. },
  40476. set: function (value) {
  40477. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40478. return;
  40479. }
  40480. StandardMaterial._DiffuseTextureEnabled = value;
  40481. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40482. },
  40483. enumerable: true,
  40484. configurable: true
  40485. });
  40486. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40487. get: function () {
  40488. return StandardMaterial._AmbientTextureEnabled;
  40489. },
  40490. set: function (value) {
  40491. if (StandardMaterial._AmbientTextureEnabled === value) {
  40492. return;
  40493. }
  40494. StandardMaterial._AmbientTextureEnabled = value;
  40495. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40496. },
  40497. enumerable: true,
  40498. configurable: true
  40499. });
  40500. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40501. get: function () {
  40502. return StandardMaterial._OpacityTextureEnabled;
  40503. },
  40504. set: function (value) {
  40505. if (StandardMaterial._OpacityTextureEnabled === value) {
  40506. return;
  40507. }
  40508. StandardMaterial._OpacityTextureEnabled = value;
  40509. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40510. },
  40511. enumerable: true,
  40512. configurable: true
  40513. });
  40514. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40515. get: function () {
  40516. return StandardMaterial._ReflectionTextureEnabled;
  40517. },
  40518. set: function (value) {
  40519. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40520. return;
  40521. }
  40522. StandardMaterial._ReflectionTextureEnabled = value;
  40523. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40524. },
  40525. enumerable: true,
  40526. configurable: true
  40527. });
  40528. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40529. get: function () {
  40530. return StandardMaterial._EmissiveTextureEnabled;
  40531. },
  40532. set: function (value) {
  40533. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40534. return;
  40535. }
  40536. StandardMaterial._EmissiveTextureEnabled = value;
  40537. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40538. },
  40539. enumerable: true,
  40540. configurable: true
  40541. });
  40542. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40543. get: function () {
  40544. return StandardMaterial._SpecularTextureEnabled;
  40545. },
  40546. set: function (value) {
  40547. if (StandardMaterial._SpecularTextureEnabled === value) {
  40548. return;
  40549. }
  40550. StandardMaterial._SpecularTextureEnabled = value;
  40551. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40552. },
  40553. enumerable: true,
  40554. configurable: true
  40555. });
  40556. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40557. get: function () {
  40558. return StandardMaterial._BumpTextureEnabled;
  40559. },
  40560. set: function (value) {
  40561. if (StandardMaterial._BumpTextureEnabled === value) {
  40562. return;
  40563. }
  40564. StandardMaterial._BumpTextureEnabled = value;
  40565. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40566. },
  40567. enumerable: true,
  40568. configurable: true
  40569. });
  40570. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40571. get: function () {
  40572. return StandardMaterial._LightmapTextureEnabled;
  40573. },
  40574. set: function (value) {
  40575. if (StandardMaterial._LightmapTextureEnabled === value) {
  40576. return;
  40577. }
  40578. StandardMaterial._LightmapTextureEnabled = value;
  40579. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40580. },
  40581. enumerable: true,
  40582. configurable: true
  40583. });
  40584. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40585. get: function () {
  40586. return StandardMaterial._RefractionTextureEnabled;
  40587. },
  40588. set: function (value) {
  40589. if (StandardMaterial._RefractionTextureEnabled === value) {
  40590. return;
  40591. }
  40592. StandardMaterial._RefractionTextureEnabled = value;
  40593. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40594. },
  40595. enumerable: true,
  40596. configurable: true
  40597. });
  40598. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40599. get: function () {
  40600. return StandardMaterial._ColorGradingTextureEnabled;
  40601. },
  40602. set: function (value) {
  40603. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40604. return;
  40605. }
  40606. StandardMaterial._ColorGradingTextureEnabled = value;
  40607. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40608. },
  40609. enumerable: true,
  40610. configurable: true
  40611. });
  40612. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40613. get: function () {
  40614. return StandardMaterial._FresnelEnabled;
  40615. },
  40616. set: function (value) {
  40617. if (StandardMaterial._FresnelEnabled === value) {
  40618. return;
  40619. }
  40620. StandardMaterial._FresnelEnabled = value;
  40621. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40622. },
  40623. enumerable: true,
  40624. configurable: true
  40625. });
  40626. // Flags used to enable or disable a type of texture for all Standard Materials
  40627. StandardMaterial._DiffuseTextureEnabled = true;
  40628. StandardMaterial._AmbientTextureEnabled = true;
  40629. StandardMaterial._OpacityTextureEnabled = true;
  40630. StandardMaterial._ReflectionTextureEnabled = true;
  40631. StandardMaterial._EmissiveTextureEnabled = true;
  40632. StandardMaterial._SpecularTextureEnabled = true;
  40633. StandardMaterial._BumpTextureEnabled = true;
  40634. StandardMaterial._LightmapTextureEnabled = true;
  40635. StandardMaterial._RefractionTextureEnabled = true;
  40636. StandardMaterial._ColorGradingTextureEnabled = true;
  40637. StandardMaterial._FresnelEnabled = true;
  40638. __decorate([
  40639. BABYLON.serializeAsTexture("diffuseTexture")
  40640. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40641. __decorate([
  40642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40643. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40644. __decorate([
  40645. BABYLON.serializeAsTexture("ambientTexture")
  40646. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40647. __decorate([
  40648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40649. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40650. __decorate([
  40651. BABYLON.serializeAsTexture("opacityTexture")
  40652. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40653. __decorate([
  40654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40655. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40656. __decorate([
  40657. BABYLON.serializeAsTexture("reflectionTexture")
  40658. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40659. __decorate([
  40660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40661. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40662. __decorate([
  40663. BABYLON.serializeAsTexture("emissiveTexture")
  40664. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40665. __decorate([
  40666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40667. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40668. __decorate([
  40669. BABYLON.serializeAsTexture("specularTexture")
  40670. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40671. __decorate([
  40672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40673. ], StandardMaterial.prototype, "specularTexture", void 0);
  40674. __decorate([
  40675. BABYLON.serializeAsTexture("bumpTexture")
  40676. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40677. __decorate([
  40678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40679. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40680. __decorate([
  40681. BABYLON.serializeAsTexture("lightmapTexture")
  40682. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40683. __decorate([
  40684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40685. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40686. __decorate([
  40687. BABYLON.serializeAsTexture("refractionTexture")
  40688. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40689. __decorate([
  40690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40691. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40692. __decorate([
  40693. BABYLON.serializeAsColor3("ambient")
  40694. ], StandardMaterial.prototype, "ambientColor", void 0);
  40695. __decorate([
  40696. BABYLON.serializeAsColor3("diffuse")
  40697. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40698. __decorate([
  40699. BABYLON.serializeAsColor3("specular")
  40700. ], StandardMaterial.prototype, "specularColor", void 0);
  40701. __decorate([
  40702. BABYLON.serializeAsColor3("emissive")
  40703. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40704. __decorate([
  40705. BABYLON.serialize()
  40706. ], StandardMaterial.prototype, "specularPower", void 0);
  40707. __decorate([
  40708. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40709. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40710. __decorate([
  40711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40712. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40713. __decorate([
  40714. BABYLON.serialize("useEmissiveAsIllumination")
  40715. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40716. __decorate([
  40717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40718. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40719. __decorate([
  40720. BABYLON.serialize("linkEmissiveWithDiffuse")
  40721. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40722. __decorate([
  40723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40724. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40725. __decorate([
  40726. BABYLON.serialize("useSpecularOverAlpha")
  40727. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40728. __decorate([
  40729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40730. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40731. __decorate([
  40732. BABYLON.serialize("useReflectionOverAlpha")
  40733. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40734. __decorate([
  40735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40736. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40737. __decorate([
  40738. BABYLON.serialize("disableLighting")
  40739. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40740. __decorate([
  40741. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40742. ], StandardMaterial.prototype, "disableLighting", void 0);
  40743. __decorate([
  40744. BABYLON.serialize("useObjectSpaceNormalMap")
  40745. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40746. __decorate([
  40747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40748. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40749. __decorate([
  40750. BABYLON.serialize("useParallax")
  40751. ], StandardMaterial.prototype, "_useParallax", void 0);
  40752. __decorate([
  40753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40754. ], StandardMaterial.prototype, "useParallax", void 0);
  40755. __decorate([
  40756. BABYLON.serialize("useParallaxOcclusion")
  40757. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40758. __decorate([
  40759. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40760. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40761. __decorate([
  40762. BABYLON.serialize()
  40763. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40764. __decorate([
  40765. BABYLON.serialize("roughness")
  40766. ], StandardMaterial.prototype, "_roughness", void 0);
  40767. __decorate([
  40768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40769. ], StandardMaterial.prototype, "roughness", void 0);
  40770. __decorate([
  40771. BABYLON.serialize()
  40772. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40773. __decorate([
  40774. BABYLON.serialize()
  40775. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40776. __decorate([
  40777. BABYLON.serialize("useLightmapAsShadowmap")
  40778. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40779. __decorate([
  40780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40781. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40782. __decorate([
  40783. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40784. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40785. __decorate([
  40786. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40787. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40788. __decorate([
  40789. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40790. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40791. __decorate([
  40792. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40793. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40794. __decorate([
  40795. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40796. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40797. __decorate([
  40798. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40799. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40800. __decorate([
  40801. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40802. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40803. __decorate([
  40804. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40805. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40806. __decorate([
  40807. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40808. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40809. __decorate([
  40810. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40811. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40812. __decorate([
  40813. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40814. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40815. __decorate([
  40816. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40817. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40818. __decorate([
  40819. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40820. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40821. __decorate([
  40822. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40823. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40824. __decorate([
  40825. BABYLON.serialize("maxSimultaneousLights")
  40826. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40827. __decorate([
  40828. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40829. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40830. __decorate([
  40831. BABYLON.serialize("invertNormalMapX")
  40832. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40833. __decorate([
  40834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40835. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40836. __decorate([
  40837. BABYLON.serialize("invertNormalMapY")
  40838. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40839. __decorate([
  40840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40841. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40842. __decorate([
  40843. BABYLON.serialize("twoSidedLighting")
  40844. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40845. __decorate([
  40846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40847. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40848. __decorate([
  40849. BABYLON.serialize()
  40850. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40851. return StandardMaterial;
  40852. }(BABYLON.PushMaterial));
  40853. BABYLON.StandardMaterial = StandardMaterial;
  40854. })(BABYLON || (BABYLON = {}));
  40855. //# sourceMappingURL=babylon.standardMaterial.js.map
  40856. "use strict";
  40857. var BABYLON;
  40858. (function (BABYLON) {
  40859. /**
  40860. * Manages the defines for the PBR Material.
  40861. */
  40862. var PBRMaterialDefines = /** @class */ (function (_super) {
  40863. __extends(PBRMaterialDefines, _super);
  40864. /**
  40865. * Initializes the PBR Material defines.
  40866. */
  40867. function PBRMaterialDefines() {
  40868. var _this = _super.call(this) || this;
  40869. _this.PBR = true;
  40870. _this.MAINUV1 = false;
  40871. _this.MAINUV2 = false;
  40872. _this.UV1 = false;
  40873. _this.UV2 = false;
  40874. _this.ALBEDO = false;
  40875. _this.ALBEDODIRECTUV = 0;
  40876. _this.VERTEXCOLOR = false;
  40877. _this.AMBIENT = false;
  40878. _this.AMBIENTDIRECTUV = 0;
  40879. _this.AMBIENTINGRAYSCALE = false;
  40880. _this.OPACITY = false;
  40881. _this.VERTEXALPHA = false;
  40882. _this.OPACITYDIRECTUV = 0;
  40883. _this.OPACITYRGB = false;
  40884. _this.ALPHATEST = false;
  40885. _this.DEPTHPREPASS = false;
  40886. _this.ALPHABLEND = false;
  40887. _this.ALPHAFROMALBEDO = false;
  40888. _this.ALPHATESTVALUE = "0.5";
  40889. _this.SPECULAROVERALPHA = false;
  40890. _this.RADIANCEOVERALPHA = false;
  40891. _this.ALPHAFRESNEL = false;
  40892. _this.LINEARALPHAFRESNEL = false;
  40893. _this.PREMULTIPLYALPHA = false;
  40894. _this.EMISSIVE = false;
  40895. _this.EMISSIVEDIRECTUV = 0;
  40896. _this.REFLECTIVITY = false;
  40897. _this.REFLECTIVITYDIRECTUV = 0;
  40898. _this.SPECULARTERM = false;
  40899. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40900. _this.MICROSURFACEAUTOMATIC = false;
  40901. _this.LODBASEDMICROSFURACE = false;
  40902. _this.MICROSURFACEMAP = false;
  40903. _this.MICROSURFACEMAPDIRECTUV = 0;
  40904. _this.METALLICWORKFLOW = false;
  40905. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40906. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40907. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40908. _this.AOSTOREINMETALMAPRED = false;
  40909. _this.ENVIRONMENTBRDF = false;
  40910. _this.NORMAL = false;
  40911. _this.TANGENT = false;
  40912. _this.BUMP = false;
  40913. _this.BUMPDIRECTUV = 0;
  40914. _this.OBJECTSPACE_NORMALMAP = false;
  40915. _this.PARALLAX = false;
  40916. _this.PARALLAXOCCLUSION = false;
  40917. _this.NORMALXYSCALE = true;
  40918. _this.LIGHTMAP = false;
  40919. _this.LIGHTMAPDIRECTUV = 0;
  40920. _this.USELIGHTMAPASSHADOWMAP = false;
  40921. _this.GAMMALIGHTMAP = false;
  40922. _this.REFLECTION = false;
  40923. _this.REFLECTIONMAP_3D = false;
  40924. _this.REFLECTIONMAP_SPHERICAL = false;
  40925. _this.REFLECTIONMAP_PLANAR = false;
  40926. _this.REFLECTIONMAP_CUBIC = false;
  40927. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40928. _this.REFLECTIONMAP_PROJECTION = false;
  40929. _this.REFLECTIONMAP_SKYBOX = false;
  40930. _this.REFLECTIONMAP_EXPLICIT = false;
  40931. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40932. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40933. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40934. _this.INVERTCUBICMAP = false;
  40935. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40936. _this.USESPHERICALINVERTEX = false;
  40937. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40938. _this.LODINREFLECTIONALPHA = false;
  40939. _this.GAMMAREFLECTION = false;
  40940. _this.RADIANCEOCCLUSION = false;
  40941. _this.HORIZONOCCLUSION = false;
  40942. _this.REFRACTION = false;
  40943. _this.REFRACTIONMAP_3D = false;
  40944. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40945. _this.LODINREFRACTIONALPHA = false;
  40946. _this.GAMMAREFRACTION = false;
  40947. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40948. _this.INSTANCES = false;
  40949. _this.NUM_BONE_INFLUENCERS = 0;
  40950. _this.BonesPerMesh = 0;
  40951. _this.NONUNIFORMSCALING = false;
  40952. _this.MORPHTARGETS = false;
  40953. _this.MORPHTARGETS_NORMAL = false;
  40954. _this.MORPHTARGETS_TANGENT = false;
  40955. _this.NUM_MORPH_INFLUENCERS = 0;
  40956. _this.IMAGEPROCESSING = false;
  40957. _this.VIGNETTE = false;
  40958. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40959. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40960. _this.TONEMAPPING = false;
  40961. _this.CONTRAST = false;
  40962. _this.COLORCURVES = false;
  40963. _this.COLORGRADING = false;
  40964. _this.COLORGRADING3D = false;
  40965. _this.SAMPLER3DGREENDEPTH = false;
  40966. _this.SAMPLER3DBGRMAP = false;
  40967. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40968. _this.EXPOSURE = false;
  40969. _this.GRAIN = false;
  40970. _this.USEPHYSICALLIGHTFALLOFF = false;
  40971. _this.TWOSIDEDLIGHTING = false;
  40972. _this.SHADOWFLOAT = false;
  40973. _this.CLIPPLANE = false;
  40974. _this.POINTSIZE = false;
  40975. _this.FOG = false;
  40976. _this.LOGARITHMICDEPTH = false;
  40977. _this.FORCENORMALFORWARD = false;
  40978. _this.UNLIT = false;
  40979. _this.rebuild();
  40980. return _this;
  40981. }
  40982. /**
  40983. * Resets the PBR Material defines.
  40984. */
  40985. PBRMaterialDefines.prototype.reset = function () {
  40986. _super.prototype.reset.call(this);
  40987. this.ALPHATESTVALUE = "0.5";
  40988. this.PBR = true;
  40989. };
  40990. return PBRMaterialDefines;
  40991. }(BABYLON.MaterialDefines));
  40992. /**
  40993. * The Physically based material base class of BJS.
  40994. *
  40995. * This offers the main features of a standard PBR material.
  40996. * For more information, please refer to the documentation :
  40997. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40998. */
  40999. var PBRBaseMaterial = /** @class */ (function (_super) {
  41000. __extends(PBRBaseMaterial, _super);
  41001. /**
  41002. * Instantiates a new PBRMaterial instance.
  41003. *
  41004. * @param name The material name
  41005. * @param scene The scene the material will be use in.
  41006. */
  41007. function PBRBaseMaterial(name, scene) {
  41008. var _this = _super.call(this, name, scene) || this;
  41009. /**
  41010. * Intensity of the direct lights e.g. the four lights available in your scene.
  41011. * This impacts both the direct diffuse and specular highlights.
  41012. */
  41013. _this._directIntensity = 1.0;
  41014. /**
  41015. * Intensity of the emissive part of the material.
  41016. * This helps controlling the emissive effect without modifying the emissive color.
  41017. */
  41018. _this._emissiveIntensity = 1.0;
  41019. /**
  41020. * Intensity of the environment e.g. how much the environment will light the object
  41021. * either through harmonics for rough material or through the refelction for shiny ones.
  41022. */
  41023. _this._environmentIntensity = 1.0;
  41024. /**
  41025. * This is a special control allowing the reduction of the specular highlights coming from the
  41026. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41027. */
  41028. _this._specularIntensity = 1.0;
  41029. /**
  41030. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41031. */
  41032. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41033. /**
  41034. * Debug Control allowing disabling the bump map on this material.
  41035. */
  41036. _this._disableBumpMap = false;
  41037. /**
  41038. * AKA Occlusion Texture Intensity in other nomenclature.
  41039. */
  41040. _this._ambientTextureStrength = 1.0;
  41041. /**
  41042. * The color of a material in ambient lighting.
  41043. */
  41044. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41045. /**
  41046. * AKA Diffuse Color in other nomenclature.
  41047. */
  41048. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41049. /**
  41050. * AKA Specular Color in other nomenclature.
  41051. */
  41052. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41053. /**
  41054. * The color applied when light is reflected from a material.
  41055. */
  41056. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41057. /**
  41058. * The color applied when light is emitted from a material.
  41059. */
  41060. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41061. /**
  41062. * AKA Glossiness in other nomenclature.
  41063. */
  41064. _this._microSurface = 0.9;
  41065. /**
  41066. * source material index of refraction (IOR)' / 'destination material IOR.
  41067. */
  41068. _this._indexOfRefraction = 0.66;
  41069. /**
  41070. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41071. */
  41072. _this._invertRefractionY = false;
  41073. /**
  41074. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41075. * Materials half opaque for instance using refraction could benefit from this control.
  41076. */
  41077. _this._linkRefractionWithTransparency = false;
  41078. /**
  41079. * Specifies that the material will use the light map as a show map.
  41080. */
  41081. _this._useLightmapAsShadowmap = false;
  41082. /**
  41083. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41084. * makes the reflect vector face the model (under horizon).
  41085. */
  41086. _this._useHorizonOcclusion = true;
  41087. /**
  41088. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41089. * too much the area relying on ambient texture to define their ambient occlusion.
  41090. */
  41091. _this._useRadianceOcclusion = true;
  41092. /**
  41093. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41094. */
  41095. _this._useAlphaFromAlbedoTexture = false;
  41096. /**
  41097. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41098. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41099. */
  41100. _this._useSpecularOverAlpha = true;
  41101. /**
  41102. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41103. */
  41104. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41105. /**
  41106. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41107. */
  41108. _this._useRoughnessFromMetallicTextureAlpha = true;
  41109. /**
  41110. * Specifies if the metallic texture contains the roughness information in its green channel.
  41111. */
  41112. _this._useRoughnessFromMetallicTextureGreen = false;
  41113. /**
  41114. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41115. */
  41116. _this._useMetallnessFromMetallicTextureBlue = false;
  41117. /**
  41118. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41119. */
  41120. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41121. /**
  41122. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41123. */
  41124. _this._useAmbientInGrayScale = false;
  41125. /**
  41126. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41127. * The material will try to infer what glossiness each pixel should be.
  41128. */
  41129. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41130. /**
  41131. * BJS is using an harcoded light falloff based on a manually sets up range.
  41132. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41133. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41134. */
  41135. _this._usePhysicalLightFalloff = true;
  41136. /**
  41137. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41138. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41139. */
  41140. _this._useRadianceOverAlpha = true;
  41141. /**
  41142. * Allows using an object space normal map (instead of tangent space).
  41143. */
  41144. _this._useObjectSpaceNormalMap = false;
  41145. /**
  41146. * Allows using the bump map in parallax mode.
  41147. */
  41148. _this._useParallax = false;
  41149. /**
  41150. * Allows using the bump map in parallax occlusion mode.
  41151. */
  41152. _this._useParallaxOcclusion = false;
  41153. /**
  41154. * Controls the scale bias of the parallax mode.
  41155. */
  41156. _this._parallaxScaleBias = 0.05;
  41157. /**
  41158. * If sets to true, disables all the lights affecting the material.
  41159. */
  41160. _this._disableLighting = false;
  41161. /**
  41162. * Number of Simultaneous lights allowed on the material.
  41163. */
  41164. _this._maxSimultaneousLights = 4;
  41165. /**
  41166. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41167. */
  41168. _this._invertNormalMapX = false;
  41169. /**
  41170. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41171. */
  41172. _this._invertNormalMapY = false;
  41173. /**
  41174. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41175. */
  41176. _this._twoSidedLighting = false;
  41177. /**
  41178. * Defines the alpha limits in alpha test mode.
  41179. */
  41180. _this._alphaCutOff = 0.4;
  41181. /**
  41182. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41183. */
  41184. _this._forceAlphaTest = false;
  41185. /**
  41186. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41187. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41188. */
  41189. _this._useAlphaFresnel = false;
  41190. /**
  41191. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41192. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41193. */
  41194. _this._useLinearAlphaFresnel = false;
  41195. /**
  41196. * The transparency mode of the material.
  41197. */
  41198. _this._transparencyMode = null;
  41199. /**
  41200. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41201. * from cos thetav and roughness:
  41202. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41203. */
  41204. _this._environmentBRDFTexture = null;
  41205. /**
  41206. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41207. */
  41208. _this._forceIrradianceInFragment = false;
  41209. /**
  41210. * Force normal to face away from face.
  41211. */
  41212. _this._forceNormalForward = false;
  41213. /**
  41214. * Stores the available render targets.
  41215. */
  41216. _this._renderTargets = new BABYLON.SmartArray(16);
  41217. /**
  41218. * Sets the global ambient color for the material used in lighting calculations.
  41219. */
  41220. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41221. /**
  41222. * If set to true, no lighting calculations will be applied.
  41223. */
  41224. _this._unlit = false;
  41225. // Setup the default processing configuration to the scene.
  41226. _this._attachImageProcessingConfiguration(null);
  41227. _this.getRenderTargetTextures = function () {
  41228. _this._renderTargets.reset();
  41229. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41230. _this._renderTargets.push(_this._reflectionTexture);
  41231. }
  41232. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41233. _this._renderTargets.push(_this._refractionTexture);
  41234. }
  41235. return _this._renderTargets;
  41236. };
  41237. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41238. return _this;
  41239. }
  41240. /**
  41241. * Attaches a new image processing configuration to the PBR Material.
  41242. * @param configuration
  41243. */
  41244. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41245. var _this = this;
  41246. if (configuration === this._imageProcessingConfiguration) {
  41247. return;
  41248. }
  41249. // Detaches observer.
  41250. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41251. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41252. }
  41253. // Pick the scene configuration if needed.
  41254. if (!configuration) {
  41255. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41256. }
  41257. else {
  41258. this._imageProcessingConfiguration = configuration;
  41259. }
  41260. // Attaches observer.
  41261. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41262. _this._markAllSubMeshesAsImageProcessingDirty();
  41263. });
  41264. };
  41265. /**
  41266. * Gets the name of the material class.
  41267. */
  41268. PBRBaseMaterial.prototype.getClassName = function () {
  41269. return "PBRBaseMaterial";
  41270. };
  41271. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41272. /**
  41273. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41274. */
  41275. get: function () {
  41276. return this._useLogarithmicDepth;
  41277. },
  41278. /**
  41279. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41280. */
  41281. set: function (value) {
  41282. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41283. },
  41284. enumerable: true,
  41285. configurable: true
  41286. });
  41287. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41288. /**
  41289. * Gets the current transparency mode.
  41290. */
  41291. get: function () {
  41292. return this._transparencyMode;
  41293. },
  41294. /**
  41295. * Sets the transparency mode of the material.
  41296. */
  41297. set: function (value) {
  41298. if (this._transparencyMode === value) {
  41299. return;
  41300. }
  41301. this._transparencyMode = value;
  41302. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41303. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41304. },
  41305. enumerable: true,
  41306. configurable: true
  41307. });
  41308. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41309. /**
  41310. * Returns true if alpha blending should be disabled.
  41311. */
  41312. get: function () {
  41313. return (this._linkRefractionWithTransparency ||
  41314. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41315. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41316. },
  41317. enumerable: true,
  41318. configurable: true
  41319. });
  41320. /**
  41321. * Specifies whether or not this material should be rendered in alpha blend mode.
  41322. */
  41323. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41324. if (this._disableAlphaBlending) {
  41325. return false;
  41326. }
  41327. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41328. };
  41329. /**
  41330. * Specifies if the mesh will require alpha blending.
  41331. * @param mesh - BJS mesh.
  41332. */
  41333. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41334. if (this._disableAlphaBlending) {
  41335. return false;
  41336. }
  41337. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41338. };
  41339. /**
  41340. * Specifies whether or not this material should be rendered in alpha test mode.
  41341. */
  41342. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41343. if (this._forceAlphaTest) {
  41344. return true;
  41345. }
  41346. if (this._linkRefractionWithTransparency) {
  41347. return false;
  41348. }
  41349. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41350. };
  41351. /**
  41352. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41353. */
  41354. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41355. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41356. };
  41357. /**
  41358. * Gets the texture used for the alpha test.
  41359. */
  41360. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41361. return this._albedoTexture;
  41362. };
  41363. /**
  41364. * Specifies that the submesh is ready to be used.
  41365. * @param mesh - BJS mesh.
  41366. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41367. * @param useInstances - Specifies that instances should be used.
  41368. * @returns - boolean indicating that the submesh is ready or not.
  41369. */
  41370. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41371. if (subMesh.effect && this.isFrozen) {
  41372. if (this._wasPreviouslyReady) {
  41373. return true;
  41374. }
  41375. }
  41376. if (!subMesh._materialDefines) {
  41377. subMesh._materialDefines = new PBRMaterialDefines();
  41378. }
  41379. var defines = subMesh._materialDefines;
  41380. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41381. if (defines._renderId === this.getScene().getRenderId()) {
  41382. return true;
  41383. }
  41384. }
  41385. var scene = this.getScene();
  41386. var engine = scene.getEngine();
  41387. if (defines._areTexturesDirty) {
  41388. if (scene.texturesEnabled) {
  41389. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41390. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41391. return false;
  41392. }
  41393. }
  41394. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41395. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41396. return false;
  41397. }
  41398. }
  41399. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41400. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41401. return false;
  41402. }
  41403. }
  41404. var reflectionTexture = this._getReflectionTexture();
  41405. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41406. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41407. return false;
  41408. }
  41409. }
  41410. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41411. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41412. return false;
  41413. }
  41414. }
  41415. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41416. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41417. return false;
  41418. }
  41419. }
  41420. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41421. if (this._metallicTexture) {
  41422. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41423. return false;
  41424. }
  41425. }
  41426. else if (this._reflectivityTexture) {
  41427. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41428. return false;
  41429. }
  41430. }
  41431. if (this._microSurfaceTexture) {
  41432. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41433. return false;
  41434. }
  41435. }
  41436. }
  41437. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41438. // Bump texture cannot be not blocking.
  41439. if (!this._bumpTexture.isReady()) {
  41440. return false;
  41441. }
  41442. }
  41443. var refractionTexture = this._getRefractionTexture();
  41444. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41445. if (!refractionTexture.isReadyOrNotBlocking()) {
  41446. return false;
  41447. }
  41448. }
  41449. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41450. // This is blocking.
  41451. if (!this._environmentBRDFTexture.isReady()) {
  41452. return false;
  41453. }
  41454. }
  41455. }
  41456. }
  41457. if (defines._areImageProcessingDirty) {
  41458. if (!this._imageProcessingConfiguration.isReady()) {
  41459. return false;
  41460. }
  41461. }
  41462. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41463. mesh.createNormals(true);
  41464. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41465. }
  41466. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41467. if (effect) {
  41468. scene.resetCachedMaterial();
  41469. subMesh.setEffect(effect, defines);
  41470. this.buildUniformLayout();
  41471. }
  41472. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41473. return false;
  41474. }
  41475. defines._renderId = scene.getRenderId();
  41476. this._wasPreviouslyReady = true;
  41477. return true;
  41478. };
  41479. /**
  41480. * Specifies if the material uses metallic roughness workflow.
  41481. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41482. */
  41483. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41484. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41485. return true;
  41486. }
  41487. return false;
  41488. };
  41489. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41490. if (onCompiled === void 0) { onCompiled = null; }
  41491. if (onError === void 0) { onError = null; }
  41492. if (useInstances === void 0) { useInstances = null; }
  41493. if (useClipPlane === void 0) { useClipPlane = null; }
  41494. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41495. if (!defines.isDirty) {
  41496. return null;
  41497. }
  41498. defines.markAsProcessed();
  41499. var scene = this.getScene();
  41500. var engine = scene.getEngine();
  41501. // Fallbacks
  41502. var fallbacks = new BABYLON.EffectFallbacks();
  41503. var fallbackRank = 0;
  41504. if (defines.USESPHERICALINVERTEX) {
  41505. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41506. }
  41507. if (defines.FOG) {
  41508. fallbacks.addFallback(fallbackRank, "FOG");
  41509. }
  41510. if (defines.POINTSIZE) {
  41511. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41512. }
  41513. if (defines.LOGARITHMICDEPTH) {
  41514. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41515. }
  41516. if (defines.PARALLAX) {
  41517. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41518. }
  41519. if (defines.PARALLAXOCCLUSION) {
  41520. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41521. }
  41522. if (defines.ENVIRONMENTBRDF) {
  41523. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41524. }
  41525. if (defines.TANGENT) {
  41526. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41527. }
  41528. if (defines.BUMP) {
  41529. fallbacks.addFallback(fallbackRank++, "BUMP");
  41530. }
  41531. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41532. if (defines.SPECULARTERM) {
  41533. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41534. }
  41535. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41536. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41537. }
  41538. if (defines.LIGHTMAP) {
  41539. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41540. }
  41541. if (defines.NORMAL) {
  41542. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41543. }
  41544. if (defines.AMBIENT) {
  41545. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41546. }
  41547. if (defines.EMISSIVE) {
  41548. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41549. }
  41550. if (defines.VERTEXCOLOR) {
  41551. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41552. }
  41553. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41554. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41555. }
  41556. if (defines.MORPHTARGETS) {
  41557. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41558. }
  41559. //Attributes
  41560. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41561. if (defines.NORMAL) {
  41562. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41563. }
  41564. if (defines.TANGENT) {
  41565. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41566. }
  41567. if (defines.UV1) {
  41568. attribs.push(BABYLON.VertexBuffer.UVKind);
  41569. }
  41570. if (defines.UV2) {
  41571. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41572. }
  41573. if (defines.VERTEXCOLOR) {
  41574. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41575. }
  41576. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41577. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41578. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41579. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41580. "vFogInfos", "vFogColor", "pointSize",
  41581. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41582. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41583. "mBones",
  41584. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41585. "vLightingIntensity",
  41586. "logarithmicDepthConstant",
  41587. "vSphericalX", "vSphericalY", "vSphericalZ",
  41588. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41589. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41590. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41591. "vTangentSpaceParams"
  41592. ];
  41593. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41594. "bumpSampler", "lightmapSampler", "opacitySampler",
  41595. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41596. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41597. "microSurfaceSampler", "environmentBrdfSampler"];
  41598. var uniformBuffers = ["Material", "Scene"];
  41599. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41600. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41601. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41602. uniformsNames: uniforms,
  41603. uniformBuffersNames: uniformBuffers,
  41604. samplers: samplers,
  41605. defines: defines,
  41606. maxSimultaneousLights: this._maxSimultaneousLights
  41607. });
  41608. var join = defines.toString();
  41609. return engine.createEffect("pbr", {
  41610. attributes: attribs,
  41611. uniformsNames: uniforms,
  41612. uniformBuffersNames: uniformBuffers,
  41613. samplers: samplers,
  41614. defines: join,
  41615. fallbacks: fallbacks,
  41616. onCompiled: onCompiled,
  41617. onError: onError,
  41618. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41619. }, engine);
  41620. };
  41621. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41622. if (useInstances === void 0) { useInstances = null; }
  41623. if (useClipPlane === void 0) { useClipPlane = null; }
  41624. var scene = this.getScene();
  41625. var engine = scene.getEngine();
  41626. // Lights
  41627. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41628. defines._needNormals = true;
  41629. // Textures
  41630. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41631. if (defines._areTexturesDirty) {
  41632. defines._needUVs = false;
  41633. if (scene.texturesEnabled) {
  41634. if (scene.getEngine().getCaps().textureLOD) {
  41635. defines.LODBASEDMICROSFURACE = true;
  41636. }
  41637. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41638. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41639. }
  41640. else {
  41641. defines.ALBEDO = false;
  41642. }
  41643. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41644. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41645. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41646. }
  41647. else {
  41648. defines.AMBIENT = false;
  41649. }
  41650. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41651. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41652. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41653. }
  41654. else {
  41655. defines.OPACITY = false;
  41656. }
  41657. var reflectionTexture = this._getReflectionTexture();
  41658. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41659. defines.REFLECTION = true;
  41660. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41661. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41662. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41663. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41664. defines.INVERTCUBICMAP = true;
  41665. }
  41666. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41667. switch (reflectionTexture.coordinatesMode) {
  41668. case BABYLON.Texture.CUBIC_MODE:
  41669. case BABYLON.Texture.INVCUBIC_MODE:
  41670. defines.REFLECTIONMAP_CUBIC = true;
  41671. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41672. break;
  41673. case BABYLON.Texture.EXPLICIT_MODE:
  41674. defines.REFLECTIONMAP_EXPLICIT = true;
  41675. break;
  41676. case BABYLON.Texture.PLANAR_MODE:
  41677. defines.REFLECTIONMAP_PLANAR = true;
  41678. break;
  41679. case BABYLON.Texture.PROJECTION_MODE:
  41680. defines.REFLECTIONMAP_PROJECTION = true;
  41681. break;
  41682. case BABYLON.Texture.SKYBOX_MODE:
  41683. defines.REFLECTIONMAP_SKYBOX = true;
  41684. break;
  41685. case BABYLON.Texture.SPHERICAL_MODE:
  41686. defines.REFLECTIONMAP_SPHERICAL = true;
  41687. break;
  41688. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41689. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41690. break;
  41691. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41692. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41693. break;
  41694. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41695. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41696. break;
  41697. }
  41698. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41699. if (reflectionTexture.sphericalPolynomial) {
  41700. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41701. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41702. defines.USESPHERICALINVERTEX = false;
  41703. }
  41704. else {
  41705. defines.USESPHERICALINVERTEX = true;
  41706. }
  41707. }
  41708. }
  41709. }
  41710. else {
  41711. defines.REFLECTION = false;
  41712. defines.REFLECTIONMAP_3D = false;
  41713. defines.REFLECTIONMAP_SPHERICAL = false;
  41714. defines.REFLECTIONMAP_PLANAR = false;
  41715. defines.REFLECTIONMAP_CUBIC = false;
  41716. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41717. defines.REFLECTIONMAP_PROJECTION = false;
  41718. defines.REFLECTIONMAP_SKYBOX = false;
  41719. defines.REFLECTIONMAP_EXPLICIT = false;
  41720. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41721. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41722. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41723. defines.INVERTCUBICMAP = false;
  41724. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41725. defines.USESPHERICALINVERTEX = false;
  41726. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41727. defines.LODINREFLECTIONALPHA = false;
  41728. defines.GAMMAREFLECTION = false;
  41729. }
  41730. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41731. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41732. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41733. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41734. }
  41735. else {
  41736. defines.LIGHTMAP = false;
  41737. }
  41738. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41739. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41740. }
  41741. else {
  41742. defines.EMISSIVE = false;
  41743. }
  41744. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41745. if (this._metallicTexture) {
  41746. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41747. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41748. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41749. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41750. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41751. }
  41752. else if (this._reflectivityTexture) {
  41753. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41754. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41755. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41756. }
  41757. else {
  41758. defines.REFLECTIVITY = false;
  41759. }
  41760. if (this._microSurfaceTexture) {
  41761. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41762. }
  41763. else {
  41764. defines.MICROSURFACEMAP = false;
  41765. }
  41766. }
  41767. else {
  41768. defines.REFLECTIVITY = false;
  41769. defines.MICROSURFACEMAP = false;
  41770. }
  41771. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41772. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41773. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41774. defines.PARALLAX = true;
  41775. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41776. }
  41777. else {
  41778. defines.PARALLAX = false;
  41779. }
  41780. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41781. }
  41782. else {
  41783. defines.BUMP = false;
  41784. }
  41785. var refractionTexture = this._getRefractionTexture();
  41786. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41787. defines.REFRACTION = true;
  41788. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41789. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41790. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41791. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41792. if (this._linkRefractionWithTransparency) {
  41793. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41794. }
  41795. }
  41796. else {
  41797. defines.REFRACTION = false;
  41798. }
  41799. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41800. defines.ENVIRONMENTBRDF = true;
  41801. }
  41802. else {
  41803. defines.ENVIRONMENTBRDF = false;
  41804. }
  41805. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41806. defines.ALPHAFROMALBEDO = true;
  41807. }
  41808. else {
  41809. defines.ALPHAFROMALBEDO = false;
  41810. }
  41811. }
  41812. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41813. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41814. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41815. if (!this.backFaceCulling && this._twoSidedLighting) {
  41816. defines.TWOSIDEDLIGHTING = true;
  41817. }
  41818. else {
  41819. defines.TWOSIDEDLIGHTING = false;
  41820. }
  41821. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41822. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41823. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41824. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41825. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41826. }
  41827. if (defines._areImageProcessingDirty) {
  41828. this._imageProcessingConfiguration.prepareDefines(defines);
  41829. }
  41830. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41831. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41832. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41833. // Misc.
  41834. if (defines._areMiscDirty) {
  41835. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41836. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41837. }
  41838. // Values that need to be evaluated on every frame
  41839. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41840. // Attribs
  41841. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41842. };
  41843. /**
  41844. * Force shader compilation
  41845. */
  41846. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41847. var _this = this;
  41848. var localOptions = __assign({ clipPlane: false }, options);
  41849. var defines = new PBRMaterialDefines();
  41850. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41851. if (effect.isReady()) {
  41852. if (onCompiled) {
  41853. onCompiled(this);
  41854. }
  41855. }
  41856. else {
  41857. effect.onCompileObservable.add(function () {
  41858. if (onCompiled) {
  41859. onCompiled(_this);
  41860. }
  41861. });
  41862. }
  41863. };
  41864. /**
  41865. * Initializes the uniform buffer layout for the shader.
  41866. */
  41867. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41868. // Order is important !
  41869. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41870. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41871. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41872. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41873. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41874. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41875. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41876. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41877. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41878. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41879. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41880. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41881. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41882. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41883. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41884. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41885. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41886. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41887. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41888. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41889. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41890. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41891. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41892. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41893. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41894. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41895. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41896. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41897. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41898. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41899. this._uniformBuffer.addUniform("pointSize", 1);
  41900. this._uniformBuffer.create();
  41901. };
  41902. /**
  41903. * Unbinds the textures.
  41904. */
  41905. PBRBaseMaterial.prototype.unbind = function () {
  41906. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41907. this._uniformBuffer.setTexture("reflectionSampler", null);
  41908. }
  41909. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41910. this._uniformBuffer.setTexture("refractionSampler", null);
  41911. }
  41912. _super.prototype.unbind.call(this);
  41913. };
  41914. /**
  41915. * Binds the submesh data.
  41916. * @param world - The world matrix.
  41917. * @param mesh - The BJS mesh.
  41918. * @param subMesh - A submesh of the BJS mesh.
  41919. */
  41920. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41921. var scene = this.getScene();
  41922. var defines = subMesh._materialDefines;
  41923. if (!defines) {
  41924. return;
  41925. }
  41926. var effect = subMesh.effect;
  41927. if (!effect) {
  41928. return;
  41929. }
  41930. this._activeEffect = effect;
  41931. // Matrices
  41932. this.bindOnlyWorldMatrix(world);
  41933. // Normal Matrix
  41934. if (defines.OBJECTSPACE_NORMALMAP) {
  41935. world.toNormalMatrix(this._normalMatrix);
  41936. this.bindOnlyNormalMatrix(this._normalMatrix);
  41937. }
  41938. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41939. // Bones
  41940. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41941. var reflectionTexture = null;
  41942. if (mustRebind) {
  41943. this._uniformBuffer.bindToEffect(effect, "Material");
  41944. this.bindViewProjection(effect);
  41945. reflectionTexture = this._getReflectionTexture();
  41946. var refractionTexture = this._getRefractionTexture();
  41947. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41948. // Texture uniforms
  41949. if (scene.texturesEnabled) {
  41950. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41951. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41952. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41953. }
  41954. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41955. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41956. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41957. }
  41958. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41959. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41960. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41961. }
  41962. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41963. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41964. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41965. if (reflectionTexture.boundingBoxSize) {
  41966. var cubeTexture = reflectionTexture;
  41967. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41968. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41969. }
  41970. var polynomials = reflectionTexture.sphericalPolynomial;
  41971. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41972. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41973. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41974. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41975. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41976. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41977. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41978. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41979. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41980. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41981. }
  41982. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41983. }
  41984. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41985. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41986. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41987. }
  41988. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41989. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41990. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41991. }
  41992. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41993. if (this._metallicTexture) {
  41994. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41995. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41996. }
  41997. else if (this._reflectivityTexture) {
  41998. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41999. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42000. }
  42001. if (this._microSurfaceTexture) {
  42002. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42003. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42004. }
  42005. }
  42006. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42007. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42008. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42009. if (scene._mirroredCameraPosition) {
  42010. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42011. }
  42012. else {
  42013. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42014. }
  42015. }
  42016. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42017. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42018. var depth = 1.0;
  42019. if (!refractionTexture.isCube) {
  42020. if (refractionTexture.depth) {
  42021. depth = refractionTexture.depth;
  42022. }
  42023. }
  42024. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42025. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42026. }
  42027. }
  42028. // Point size
  42029. if (this.pointsCloud) {
  42030. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42031. }
  42032. // Colors
  42033. if (defines.METALLICWORKFLOW) {
  42034. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42035. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42036. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42037. }
  42038. else {
  42039. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42040. }
  42041. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42042. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42043. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42044. // Misc
  42045. this._lightingInfos.x = this._directIntensity;
  42046. this._lightingInfos.y = this._emissiveIntensity;
  42047. this._lightingInfos.z = this._environmentIntensity;
  42048. this._lightingInfos.w = this._specularIntensity;
  42049. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42050. }
  42051. // Textures
  42052. if (scene.texturesEnabled) {
  42053. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42054. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42055. }
  42056. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42057. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42058. }
  42059. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42060. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42061. }
  42062. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42063. if (defines.LODBASEDMICROSFURACE) {
  42064. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42065. }
  42066. else {
  42067. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42068. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42069. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42070. }
  42071. }
  42072. if (defines.ENVIRONMENTBRDF) {
  42073. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42074. }
  42075. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42076. if (defines.LODBASEDMICROSFURACE) {
  42077. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42078. }
  42079. else {
  42080. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42081. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42082. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42083. }
  42084. }
  42085. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42086. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42087. }
  42088. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42089. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42090. }
  42091. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42092. if (this._metallicTexture) {
  42093. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42094. }
  42095. else if (this._reflectivityTexture) {
  42096. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42097. }
  42098. if (this._microSurfaceTexture) {
  42099. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42100. }
  42101. }
  42102. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42103. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42104. }
  42105. }
  42106. // Clip plane
  42107. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42108. // Colors
  42109. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42110. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42111. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42112. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42113. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42114. }
  42115. if (mustRebind || !this.isFrozen) {
  42116. // Lights
  42117. if (scene.lightsEnabled && !this._disableLighting) {
  42118. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42119. }
  42120. // View
  42121. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42122. this.bindView(effect);
  42123. }
  42124. // Fog
  42125. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42126. // Morph targets
  42127. if (defines.NUM_MORPH_INFLUENCERS) {
  42128. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42129. }
  42130. // image processing
  42131. this._imageProcessingConfiguration.bind(this._activeEffect);
  42132. // Log. depth
  42133. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42134. }
  42135. this._uniformBuffer.update();
  42136. this._afterBind(mesh);
  42137. };
  42138. /**
  42139. * Returns the animatable textures.
  42140. * @returns - Array of animatable textures.
  42141. */
  42142. PBRBaseMaterial.prototype.getAnimatables = function () {
  42143. var results = [];
  42144. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42145. results.push(this._albedoTexture);
  42146. }
  42147. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42148. results.push(this._ambientTexture);
  42149. }
  42150. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42151. results.push(this._opacityTexture);
  42152. }
  42153. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42154. results.push(this._reflectionTexture);
  42155. }
  42156. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42157. results.push(this._emissiveTexture);
  42158. }
  42159. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42160. results.push(this._metallicTexture);
  42161. }
  42162. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42163. results.push(this._reflectivityTexture);
  42164. }
  42165. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42166. results.push(this._bumpTexture);
  42167. }
  42168. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42169. results.push(this._lightmapTexture);
  42170. }
  42171. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42172. results.push(this._refractionTexture);
  42173. }
  42174. return results;
  42175. };
  42176. /**
  42177. * Returns the texture used for reflections.
  42178. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42179. */
  42180. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42181. if (this._reflectionTexture) {
  42182. return this._reflectionTexture;
  42183. }
  42184. return this.getScene().environmentTexture;
  42185. };
  42186. /**
  42187. * Returns the texture used for refraction or null if none is used.
  42188. * @returns - Refection texture if present. If no refraction texture and refraction
  42189. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42190. */
  42191. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42192. if (this._refractionTexture) {
  42193. return this._refractionTexture;
  42194. }
  42195. if (this._linkRefractionWithTransparency) {
  42196. return this.getScene().environmentTexture;
  42197. }
  42198. return null;
  42199. };
  42200. /**
  42201. * Disposes the resources of the material.
  42202. * @param forceDisposeEffect - Forces the disposal of effects.
  42203. * @param forceDisposeTextures - Forces the disposal of all textures.
  42204. */
  42205. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42206. if (forceDisposeTextures) {
  42207. if (this._albedoTexture) {
  42208. this._albedoTexture.dispose();
  42209. }
  42210. if (this._ambientTexture) {
  42211. this._ambientTexture.dispose();
  42212. }
  42213. if (this._opacityTexture) {
  42214. this._opacityTexture.dispose();
  42215. }
  42216. if (this._reflectionTexture) {
  42217. this._reflectionTexture.dispose();
  42218. }
  42219. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42220. this._environmentBRDFTexture.dispose();
  42221. }
  42222. if (this._emissiveTexture) {
  42223. this._emissiveTexture.dispose();
  42224. }
  42225. if (this._metallicTexture) {
  42226. this._metallicTexture.dispose();
  42227. }
  42228. if (this._reflectivityTexture) {
  42229. this._reflectivityTexture.dispose();
  42230. }
  42231. if (this._bumpTexture) {
  42232. this._bumpTexture.dispose();
  42233. }
  42234. if (this._lightmapTexture) {
  42235. this._lightmapTexture.dispose();
  42236. }
  42237. if (this._refractionTexture) {
  42238. this._refractionTexture.dispose();
  42239. }
  42240. }
  42241. this._renderTargets.dispose();
  42242. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42243. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42244. }
  42245. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42246. };
  42247. /**
  42248. * Stores the reflectivity values based on metallic roughness workflow.
  42249. */
  42250. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42251. __decorate([
  42252. BABYLON.serializeAsImageProcessingConfiguration()
  42253. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42254. __decorate([
  42255. BABYLON.serialize()
  42256. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42257. __decorate([
  42258. BABYLON.serialize()
  42259. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42260. return PBRBaseMaterial;
  42261. }(BABYLON.PushMaterial));
  42262. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42263. })(BABYLON || (BABYLON = {}));
  42264. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42265. "use strict";
  42266. var BABYLON;
  42267. (function (BABYLON) {
  42268. /**
  42269. * The Physically based simple base material of BJS.
  42270. *
  42271. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42272. * It is used as the base class for both the specGloss and metalRough conventions.
  42273. */
  42274. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42275. __extends(PBRBaseSimpleMaterial, _super);
  42276. /**
  42277. * Instantiates a new PBRMaterial instance.
  42278. *
  42279. * @param name The material name
  42280. * @param scene The scene the material will be use in.
  42281. */
  42282. function PBRBaseSimpleMaterial(name, scene) {
  42283. var _this = _super.call(this, name, scene) || this;
  42284. /**
  42285. * Number of Simultaneous lights allowed on the material.
  42286. */
  42287. _this.maxSimultaneousLights = 4;
  42288. /**
  42289. * If sets to true, disables all the lights affecting the material.
  42290. */
  42291. _this.disableLighting = false;
  42292. /**
  42293. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42294. */
  42295. _this.invertNormalMapX = false;
  42296. /**
  42297. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42298. */
  42299. _this.invertNormalMapY = false;
  42300. /**
  42301. * Emissivie color used to self-illuminate the model.
  42302. */
  42303. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42304. /**
  42305. * Occlusion Channel Strenght.
  42306. */
  42307. _this.occlusionStrength = 1.0;
  42308. _this.useLightmapAsShadowmap = false;
  42309. _this._useAlphaFromAlbedoTexture = true;
  42310. _this._useAmbientInGrayScale = true;
  42311. return _this;
  42312. }
  42313. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42314. /**
  42315. * Gets the current double sided mode.
  42316. */
  42317. get: function () {
  42318. return this._twoSidedLighting;
  42319. },
  42320. /**
  42321. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42322. */
  42323. set: function (value) {
  42324. if (this._twoSidedLighting === value) {
  42325. return;
  42326. }
  42327. this._twoSidedLighting = value;
  42328. this.backFaceCulling = !value;
  42329. this._markAllSubMeshesAsTexturesDirty();
  42330. },
  42331. enumerable: true,
  42332. configurable: true
  42333. });
  42334. /**
  42335. * Return the active textures of the material.
  42336. */
  42337. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42338. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42339. if (this.environmentTexture) {
  42340. activeTextures.push(this.environmentTexture);
  42341. }
  42342. if (this.normalTexture) {
  42343. activeTextures.push(this.normalTexture);
  42344. }
  42345. if (this.emissiveTexture) {
  42346. activeTextures.push(this.emissiveTexture);
  42347. }
  42348. if (this.occlusionTexture) {
  42349. activeTextures.push(this.occlusionTexture);
  42350. }
  42351. if (this.lightmapTexture) {
  42352. activeTextures.push(this.lightmapTexture);
  42353. }
  42354. return activeTextures;
  42355. };
  42356. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42357. if (_super.prototype.hasTexture.call(this, texture)) {
  42358. return true;
  42359. }
  42360. if (this.lightmapTexture === texture) {
  42361. return true;
  42362. }
  42363. return false;
  42364. };
  42365. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42366. return "PBRBaseSimpleMaterial";
  42367. };
  42368. __decorate([
  42369. BABYLON.serialize(),
  42370. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42371. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42372. __decorate([
  42373. BABYLON.serialize(),
  42374. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42375. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42376. __decorate([
  42377. BABYLON.serializeAsTexture(),
  42378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42379. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42380. __decorate([
  42381. BABYLON.serialize(),
  42382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42383. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42384. __decorate([
  42385. BABYLON.serialize(),
  42386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42387. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42388. __decorate([
  42389. BABYLON.serializeAsTexture(),
  42390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42391. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42392. __decorate([
  42393. BABYLON.serializeAsColor3("emissive"),
  42394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42395. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42396. __decorate([
  42397. BABYLON.serializeAsTexture(),
  42398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42399. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42400. __decorate([
  42401. BABYLON.serialize(),
  42402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42403. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42404. __decorate([
  42405. BABYLON.serializeAsTexture(),
  42406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42407. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42408. __decorate([
  42409. BABYLON.serialize(),
  42410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42411. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42412. __decorate([
  42413. BABYLON.serialize()
  42414. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42415. __decorate([
  42416. BABYLON.serializeAsTexture(),
  42417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42418. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42419. __decorate([
  42420. BABYLON.serialize(),
  42421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42422. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42423. return PBRBaseSimpleMaterial;
  42424. }(BABYLON.PBRBaseMaterial));
  42425. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42426. })(BABYLON || (BABYLON = {}));
  42427. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42428. "use strict";
  42429. var BABYLON;
  42430. (function (BABYLON) {
  42431. /**
  42432. * The Physically based material of BJS.
  42433. *
  42434. * This offers the main features of a standard PBR material.
  42435. * For more information, please refer to the documentation :
  42436. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42437. */
  42438. var PBRMaterial = /** @class */ (function (_super) {
  42439. __extends(PBRMaterial, _super);
  42440. /**
  42441. * Instantiates a new PBRMaterial instance.
  42442. *
  42443. * @param name The material name
  42444. * @param scene The scene the material will be use in.
  42445. */
  42446. function PBRMaterial(name, scene) {
  42447. var _this = _super.call(this, name, scene) || this;
  42448. /**
  42449. * Intensity of the direct lights e.g. the four lights available in your scene.
  42450. * This impacts both the direct diffuse and specular highlights.
  42451. */
  42452. _this.directIntensity = 1.0;
  42453. /**
  42454. * Intensity of the emissive part of the material.
  42455. * This helps controlling the emissive effect without modifying the emissive color.
  42456. */
  42457. _this.emissiveIntensity = 1.0;
  42458. /**
  42459. * Intensity of the environment e.g. how much the environment will light the object
  42460. * either through harmonics for rough material or through the refelction for shiny ones.
  42461. */
  42462. _this.environmentIntensity = 1.0;
  42463. /**
  42464. * This is a special control allowing the reduction of the specular highlights coming from the
  42465. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42466. */
  42467. _this.specularIntensity = 1.0;
  42468. /**
  42469. * Debug Control allowing disabling the bump map on this material.
  42470. */
  42471. _this.disableBumpMap = false;
  42472. /**
  42473. * AKA Occlusion Texture Intensity in other nomenclature.
  42474. */
  42475. _this.ambientTextureStrength = 1.0;
  42476. /**
  42477. * The color of a material in ambient lighting.
  42478. */
  42479. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42480. /**
  42481. * AKA Diffuse Color in other nomenclature.
  42482. */
  42483. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42484. /**
  42485. * AKA Specular Color in other nomenclature.
  42486. */
  42487. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42488. /**
  42489. * The color reflected from the material.
  42490. */
  42491. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42492. /**
  42493. * The color emitted from the material.
  42494. */
  42495. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42496. /**
  42497. * AKA Glossiness in other nomenclature.
  42498. */
  42499. _this.microSurface = 1.0;
  42500. /**
  42501. * source material index of refraction (IOR)' / 'destination material IOR.
  42502. */
  42503. _this.indexOfRefraction = 0.66;
  42504. /**
  42505. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42506. */
  42507. _this.invertRefractionY = false;
  42508. /**
  42509. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42510. * Materials half opaque for instance using refraction could benefit from this control.
  42511. */
  42512. _this.linkRefractionWithTransparency = false;
  42513. _this.useLightmapAsShadowmap = false;
  42514. /**
  42515. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42516. */
  42517. _this.useAlphaFromAlbedoTexture = false;
  42518. /**
  42519. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42520. */
  42521. _this.forceAlphaTest = false;
  42522. /**
  42523. * Defines the alpha limits in alpha test mode.
  42524. */
  42525. _this.alphaCutOff = 0.4;
  42526. /**
  42527. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42528. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42529. */
  42530. _this.useSpecularOverAlpha = true;
  42531. /**
  42532. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42533. */
  42534. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42535. /**
  42536. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42537. */
  42538. _this.useRoughnessFromMetallicTextureAlpha = true;
  42539. /**
  42540. * Specifies if the metallic texture contains the roughness information in its green channel.
  42541. */
  42542. _this.useRoughnessFromMetallicTextureGreen = false;
  42543. /**
  42544. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42545. */
  42546. _this.useMetallnessFromMetallicTextureBlue = false;
  42547. /**
  42548. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42549. */
  42550. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42551. /**
  42552. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42553. */
  42554. _this.useAmbientInGrayScale = false;
  42555. /**
  42556. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42557. * The material will try to infer what glossiness each pixel should be.
  42558. */
  42559. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42560. /**
  42561. * BJS is using an harcoded light falloff based on a manually sets up range.
  42562. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42563. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42564. */
  42565. _this.usePhysicalLightFalloff = true;
  42566. /**
  42567. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42568. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42569. */
  42570. _this.useRadianceOverAlpha = true;
  42571. /**
  42572. * Allows using an object space normal map (instead of tangent space).
  42573. */
  42574. _this.useObjectSpaceNormalMap = false;
  42575. /**
  42576. * Allows using the bump map in parallax mode.
  42577. */
  42578. _this.useParallax = false;
  42579. /**
  42580. * Allows using the bump map in parallax occlusion mode.
  42581. */
  42582. _this.useParallaxOcclusion = false;
  42583. /**
  42584. * Controls the scale bias of the parallax mode.
  42585. */
  42586. _this.parallaxScaleBias = 0.05;
  42587. /**
  42588. * If sets to true, disables all the lights affecting the material.
  42589. */
  42590. _this.disableLighting = false;
  42591. /**
  42592. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42593. */
  42594. _this.forceIrradianceInFragment = false;
  42595. /**
  42596. * Number of Simultaneous lights allowed on the material.
  42597. */
  42598. _this.maxSimultaneousLights = 4;
  42599. /**
  42600. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42601. */
  42602. _this.invertNormalMapX = false;
  42603. /**
  42604. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42605. */
  42606. _this.invertNormalMapY = false;
  42607. /**
  42608. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42609. */
  42610. _this.twoSidedLighting = false;
  42611. /**
  42612. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42613. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42614. */
  42615. _this.useAlphaFresnel = false;
  42616. /**
  42617. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42618. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42619. */
  42620. _this.useLinearAlphaFresnel = false;
  42621. /**
  42622. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42623. * And/Or occlude the blended part.
  42624. */
  42625. _this.environmentBRDFTexture = null;
  42626. /**
  42627. * Force normal to face away from face.
  42628. */
  42629. _this.forceNormalForward = false;
  42630. /**
  42631. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42632. * makes the reflect vector face the model (under horizon).
  42633. */
  42634. _this.useHorizonOcclusion = true;
  42635. /**
  42636. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42637. * too much the area relying on ambient texture to define their ambient occlusion.
  42638. */
  42639. _this.useRadianceOcclusion = true;
  42640. /**
  42641. * If set to true, no lighting calculations will be applied.
  42642. */
  42643. _this.unlit = false;
  42644. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42645. return _this;
  42646. }
  42647. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42648. /**
  42649. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42650. */
  42651. get: function () {
  42652. return this._PBRMATERIAL_OPAQUE;
  42653. },
  42654. enumerable: true,
  42655. configurable: true
  42656. });
  42657. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42658. /**
  42659. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42660. */
  42661. get: function () {
  42662. return this._PBRMATERIAL_ALPHATEST;
  42663. },
  42664. enumerable: true,
  42665. configurable: true
  42666. });
  42667. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42668. /**
  42669. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42670. */
  42671. get: function () {
  42672. return this._PBRMATERIAL_ALPHABLEND;
  42673. },
  42674. enumerable: true,
  42675. configurable: true
  42676. });
  42677. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42678. /**
  42679. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42680. * They are also discarded below the alpha cutoff threshold to improve performances.
  42681. */
  42682. get: function () {
  42683. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42684. },
  42685. enumerable: true,
  42686. configurable: true
  42687. });
  42688. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42689. /**
  42690. * Gets the image processing configuration used either in this material.
  42691. */
  42692. get: function () {
  42693. return this._imageProcessingConfiguration;
  42694. },
  42695. /**
  42696. * Sets the Default image processing configuration used either in the this material.
  42697. *
  42698. * If sets to null, the scene one is in use.
  42699. */
  42700. set: function (value) {
  42701. this._attachImageProcessingConfiguration(value);
  42702. // Ensure the effect will be rebuilt.
  42703. this._markAllSubMeshesAsTexturesDirty();
  42704. },
  42705. enumerable: true,
  42706. configurable: true
  42707. });
  42708. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42709. /**
  42710. * Gets wether the color curves effect is enabled.
  42711. */
  42712. get: function () {
  42713. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42714. },
  42715. /**
  42716. * Sets wether the color curves effect is enabled.
  42717. */
  42718. set: function (value) {
  42719. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42720. },
  42721. enumerable: true,
  42722. configurable: true
  42723. });
  42724. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42725. /**
  42726. * Gets wether the color grading effect is enabled.
  42727. */
  42728. get: function () {
  42729. return this.imageProcessingConfiguration.colorGradingEnabled;
  42730. },
  42731. /**
  42732. * Gets wether the color grading effect is enabled.
  42733. */
  42734. set: function (value) {
  42735. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42736. },
  42737. enumerable: true,
  42738. configurable: true
  42739. });
  42740. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42741. /**
  42742. * Gets wether tonemapping is enabled or not.
  42743. */
  42744. get: function () {
  42745. return this._imageProcessingConfiguration.toneMappingEnabled;
  42746. },
  42747. /**
  42748. * Sets wether tonemapping is enabled or not
  42749. */
  42750. set: function (value) {
  42751. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42752. },
  42753. enumerable: true,
  42754. configurable: true
  42755. });
  42756. ;
  42757. ;
  42758. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42759. /**
  42760. * The camera exposure used on this material.
  42761. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42762. * This corresponds to a photographic exposure.
  42763. */
  42764. get: function () {
  42765. return this._imageProcessingConfiguration.exposure;
  42766. },
  42767. /**
  42768. * The camera exposure used on this material.
  42769. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42770. * This corresponds to a photographic exposure.
  42771. */
  42772. set: function (value) {
  42773. this._imageProcessingConfiguration.exposure = value;
  42774. },
  42775. enumerable: true,
  42776. configurable: true
  42777. });
  42778. ;
  42779. ;
  42780. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42781. /**
  42782. * Gets The camera contrast used on this material.
  42783. */
  42784. get: function () {
  42785. return this._imageProcessingConfiguration.contrast;
  42786. },
  42787. /**
  42788. * Sets The camera contrast used on this material.
  42789. */
  42790. set: function (value) {
  42791. this._imageProcessingConfiguration.contrast = value;
  42792. },
  42793. enumerable: true,
  42794. configurable: true
  42795. });
  42796. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42797. /**
  42798. * Gets the Color Grading 2D Lookup Texture.
  42799. */
  42800. get: function () {
  42801. return this._imageProcessingConfiguration.colorGradingTexture;
  42802. },
  42803. /**
  42804. * Sets the Color Grading 2D Lookup Texture.
  42805. */
  42806. set: function (value) {
  42807. this._imageProcessingConfiguration.colorGradingTexture = value;
  42808. },
  42809. enumerable: true,
  42810. configurable: true
  42811. });
  42812. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42813. /**
  42814. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42815. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42816. * 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;
  42817. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42818. */
  42819. get: function () {
  42820. return this._imageProcessingConfiguration.colorCurves;
  42821. },
  42822. /**
  42823. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42824. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42825. * 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;
  42826. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42827. */
  42828. set: function (value) {
  42829. this._imageProcessingConfiguration.colorCurves = value;
  42830. },
  42831. enumerable: true,
  42832. configurable: true
  42833. });
  42834. /**
  42835. * Returns the name of this material class.
  42836. */
  42837. PBRMaterial.prototype.getClassName = function () {
  42838. return "PBRMaterial";
  42839. };
  42840. /**
  42841. * Returns an array of the actively used textures.
  42842. * @returns - Array of BaseTextures
  42843. */
  42844. PBRMaterial.prototype.getActiveTextures = function () {
  42845. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42846. if (this._albedoTexture) {
  42847. activeTextures.push(this._albedoTexture);
  42848. }
  42849. if (this._ambientTexture) {
  42850. activeTextures.push(this._ambientTexture);
  42851. }
  42852. if (this._opacityTexture) {
  42853. activeTextures.push(this._opacityTexture);
  42854. }
  42855. if (this._reflectionTexture) {
  42856. activeTextures.push(this._reflectionTexture);
  42857. }
  42858. if (this._emissiveTexture) {
  42859. activeTextures.push(this._emissiveTexture);
  42860. }
  42861. if (this._reflectivityTexture) {
  42862. activeTextures.push(this._reflectivityTexture);
  42863. }
  42864. if (this._metallicTexture) {
  42865. activeTextures.push(this._metallicTexture);
  42866. }
  42867. if (this._microSurfaceTexture) {
  42868. activeTextures.push(this._microSurfaceTexture);
  42869. }
  42870. if (this._bumpTexture) {
  42871. activeTextures.push(this._bumpTexture);
  42872. }
  42873. if (this._lightmapTexture) {
  42874. activeTextures.push(this._lightmapTexture);
  42875. }
  42876. if (this._refractionTexture) {
  42877. activeTextures.push(this._refractionTexture);
  42878. }
  42879. return activeTextures;
  42880. };
  42881. /**
  42882. * Checks to see if a texture is used in the material.
  42883. * @param texture - Base texture to use.
  42884. * @returns - Boolean specifying if a texture is used in the material.
  42885. */
  42886. PBRMaterial.prototype.hasTexture = function (texture) {
  42887. if (_super.prototype.hasTexture.call(this, texture)) {
  42888. return true;
  42889. }
  42890. if (this._albedoTexture === texture) {
  42891. return true;
  42892. }
  42893. if (this._ambientTexture === texture) {
  42894. return true;
  42895. }
  42896. if (this._opacityTexture === texture) {
  42897. return true;
  42898. }
  42899. if (this._reflectionTexture === texture) {
  42900. return true;
  42901. }
  42902. if (this._reflectivityTexture === texture) {
  42903. return true;
  42904. }
  42905. if (this._metallicTexture === texture) {
  42906. return true;
  42907. }
  42908. if (this._microSurfaceTexture === texture) {
  42909. return true;
  42910. }
  42911. if (this._bumpTexture === texture) {
  42912. return true;
  42913. }
  42914. if (this._lightmapTexture === texture) {
  42915. return true;
  42916. }
  42917. if (this._refractionTexture === texture) {
  42918. return true;
  42919. }
  42920. return false;
  42921. };
  42922. /**
  42923. * Makes a duplicate of the current material.
  42924. * @param name - name to use for the new material.
  42925. */
  42926. PBRMaterial.prototype.clone = function (name) {
  42927. var _this = this;
  42928. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42929. clone.id = name;
  42930. clone.name = name;
  42931. return clone;
  42932. };
  42933. /**
  42934. * Serializes this PBR Material.
  42935. * @returns - An object with the serialized material.
  42936. */
  42937. PBRMaterial.prototype.serialize = function () {
  42938. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42939. serializationObject.customType = "BABYLON.PBRMaterial";
  42940. return serializationObject;
  42941. };
  42942. // Statics
  42943. /**
  42944. * Parses a PBR Material from a serialized object.
  42945. * @param source - Serialized object.
  42946. * @param scene - BJS scene instance.
  42947. * @param rootUrl - url for the scene object
  42948. * @returns - PBRMaterial
  42949. */
  42950. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42951. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42952. };
  42953. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42954. /**
  42955. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42956. */
  42957. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42958. /**
  42959. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42960. */
  42961. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42962. /**
  42963. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42964. * They are also discarded below the alpha cutoff threshold to improve performances.
  42965. */
  42966. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42967. __decorate([
  42968. BABYLON.serialize(),
  42969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42970. ], PBRMaterial.prototype, "directIntensity", void 0);
  42971. __decorate([
  42972. BABYLON.serialize(),
  42973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42974. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42975. __decorate([
  42976. BABYLON.serialize(),
  42977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42978. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42979. __decorate([
  42980. BABYLON.serialize(),
  42981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42982. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42983. __decorate([
  42984. BABYLON.serialize(),
  42985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42986. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42987. __decorate([
  42988. BABYLON.serializeAsTexture(),
  42989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42990. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42991. __decorate([
  42992. BABYLON.serializeAsTexture(),
  42993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42994. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42995. __decorate([
  42996. BABYLON.serialize(),
  42997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42998. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42999. __decorate([
  43000. BABYLON.serializeAsTexture(),
  43001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43002. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43003. __decorate([
  43004. BABYLON.serializeAsTexture(),
  43005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43006. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43007. __decorate([
  43008. BABYLON.serializeAsTexture(),
  43009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43010. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43011. __decorate([
  43012. BABYLON.serializeAsTexture(),
  43013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43014. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43015. __decorate([
  43016. BABYLON.serializeAsTexture(),
  43017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43018. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43019. __decorate([
  43020. BABYLON.serialize(),
  43021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43022. ], PBRMaterial.prototype, "metallic", void 0);
  43023. __decorate([
  43024. BABYLON.serialize(),
  43025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43026. ], PBRMaterial.prototype, "roughness", void 0);
  43027. __decorate([
  43028. BABYLON.serializeAsTexture(),
  43029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43030. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43031. __decorate([
  43032. BABYLON.serializeAsTexture(),
  43033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43034. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43035. __decorate([
  43036. BABYLON.serializeAsTexture(),
  43037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43038. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43039. __decorate([
  43040. BABYLON.serializeAsTexture(),
  43041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43042. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43043. __decorate([
  43044. BABYLON.serializeAsColor3("ambient"),
  43045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43046. ], PBRMaterial.prototype, "ambientColor", void 0);
  43047. __decorate([
  43048. BABYLON.serializeAsColor3("albedo"),
  43049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43050. ], PBRMaterial.prototype, "albedoColor", void 0);
  43051. __decorate([
  43052. BABYLON.serializeAsColor3("reflectivity"),
  43053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43054. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43055. __decorate([
  43056. BABYLON.serializeAsColor3("reflection"),
  43057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43058. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43059. __decorate([
  43060. BABYLON.serializeAsColor3("emissive"),
  43061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43062. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43063. __decorate([
  43064. BABYLON.serialize(),
  43065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43066. ], PBRMaterial.prototype, "microSurface", void 0);
  43067. __decorate([
  43068. BABYLON.serialize(),
  43069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43070. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43071. __decorate([
  43072. BABYLON.serialize(),
  43073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43074. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43075. __decorate([
  43076. BABYLON.serialize(),
  43077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43078. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43079. __decorate([
  43080. BABYLON.serialize(),
  43081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43082. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43083. __decorate([
  43084. BABYLON.serialize(),
  43085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43086. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43087. __decorate([
  43088. BABYLON.serialize(),
  43089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43090. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43091. __decorate([
  43092. BABYLON.serialize(),
  43093. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43094. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43095. __decorate([
  43096. BABYLON.serialize(),
  43097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43098. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43099. __decorate([
  43100. BABYLON.serialize(),
  43101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43102. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43103. __decorate([
  43104. BABYLON.serialize(),
  43105. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43106. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43107. __decorate([
  43108. BABYLON.serialize(),
  43109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43110. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43111. __decorate([
  43112. BABYLON.serialize(),
  43113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43114. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43115. __decorate([
  43116. BABYLON.serialize(),
  43117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43118. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43119. __decorate([
  43120. BABYLON.serialize(),
  43121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43122. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43123. __decorate([
  43124. BABYLON.serialize(),
  43125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43126. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43127. __decorate([
  43128. BABYLON.serialize(),
  43129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43130. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43131. __decorate([
  43132. BABYLON.serialize(),
  43133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43134. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43135. __decorate([
  43136. BABYLON.serialize(),
  43137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43138. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43139. __decorate([
  43140. BABYLON.serialize(),
  43141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43142. ], PBRMaterial.prototype, "useParallax", void 0);
  43143. __decorate([
  43144. BABYLON.serialize(),
  43145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43146. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43147. __decorate([
  43148. BABYLON.serialize(),
  43149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43150. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43151. __decorate([
  43152. BABYLON.serialize(),
  43153. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43154. ], PBRMaterial.prototype, "disableLighting", void 0);
  43155. __decorate([
  43156. BABYLON.serialize(),
  43157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43158. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43159. __decorate([
  43160. BABYLON.serialize(),
  43161. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43162. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43163. __decorate([
  43164. BABYLON.serialize(),
  43165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43166. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43167. __decorate([
  43168. BABYLON.serialize(),
  43169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43170. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43171. __decorate([
  43172. BABYLON.serialize(),
  43173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43174. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43175. __decorate([
  43176. BABYLON.serialize(),
  43177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43178. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43179. __decorate([
  43180. BABYLON.serialize(),
  43181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43182. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43183. __decorate([
  43184. BABYLON.serializeAsTexture(),
  43185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43186. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43187. __decorate([
  43188. BABYLON.serialize(),
  43189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43190. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43191. __decorate([
  43192. BABYLON.serialize(),
  43193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43194. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43195. __decorate([
  43196. BABYLON.serialize(),
  43197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43198. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43199. __decorate([
  43200. BABYLON.serialize(),
  43201. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43202. ], PBRMaterial.prototype, "unlit", void 0);
  43203. return PBRMaterial;
  43204. }(BABYLON.PBRBaseMaterial));
  43205. BABYLON.PBRMaterial = PBRMaterial;
  43206. })(BABYLON || (BABYLON = {}));
  43207. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43208. "use strict";
  43209. var BABYLON;
  43210. (function (BABYLON) {
  43211. /**
  43212. * The PBR material of BJS following the metal roughness convention.
  43213. *
  43214. * This fits to the PBR convention in the GLTF definition:
  43215. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43216. */
  43217. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43218. __extends(PBRMetallicRoughnessMaterial, _super);
  43219. /**
  43220. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43221. *
  43222. * @param name The material name
  43223. * @param scene The scene the material will be use in.
  43224. */
  43225. function PBRMetallicRoughnessMaterial(name, scene) {
  43226. var _this = _super.call(this, name, scene) || this;
  43227. _this._useRoughnessFromMetallicTextureAlpha = false;
  43228. _this._useRoughnessFromMetallicTextureGreen = true;
  43229. _this._useMetallnessFromMetallicTextureBlue = true;
  43230. _this.metallic = 1.0;
  43231. _this.roughness = 1.0;
  43232. return _this;
  43233. }
  43234. /**
  43235. * Return the currrent class name of the material.
  43236. */
  43237. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43238. return "PBRMetallicRoughnessMaterial";
  43239. };
  43240. /**
  43241. * Return the active textures of the material.
  43242. */
  43243. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43244. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43245. if (this.baseTexture) {
  43246. activeTextures.push(this.baseTexture);
  43247. }
  43248. if (this.metallicRoughnessTexture) {
  43249. activeTextures.push(this.metallicRoughnessTexture);
  43250. }
  43251. return activeTextures;
  43252. };
  43253. /**
  43254. * Checks to see if a texture is used in the material.
  43255. * @param texture - Base texture to use.
  43256. * @returns - Boolean specifying if a texture is used in the material.
  43257. */
  43258. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43259. if (_super.prototype.hasTexture.call(this, texture)) {
  43260. return true;
  43261. }
  43262. if (this.baseTexture === texture) {
  43263. return true;
  43264. }
  43265. if (this.metallicRoughnessTexture === texture) {
  43266. return true;
  43267. }
  43268. return false;
  43269. };
  43270. /**
  43271. * Makes a duplicate of the current material.
  43272. * @param name - name to use for the new material.
  43273. */
  43274. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43275. var _this = this;
  43276. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43277. clone.id = name;
  43278. clone.name = name;
  43279. return clone;
  43280. };
  43281. /**
  43282. * Serialize the material to a parsable JSON object.
  43283. */
  43284. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43285. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43286. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43287. return serializationObject;
  43288. };
  43289. /**
  43290. * Parses a JSON object correponding to the serialize function.
  43291. */
  43292. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43293. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43294. };
  43295. __decorate([
  43296. BABYLON.serializeAsColor3(),
  43297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43298. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43299. __decorate([
  43300. BABYLON.serializeAsTexture(),
  43301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43302. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43303. __decorate([
  43304. BABYLON.serialize(),
  43305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43306. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43307. __decorate([
  43308. BABYLON.serialize(),
  43309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43310. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43311. __decorate([
  43312. BABYLON.serializeAsTexture(),
  43313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43314. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43315. return PBRMetallicRoughnessMaterial;
  43316. }(BABYLON.PBRBaseSimpleMaterial));
  43317. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43318. })(BABYLON || (BABYLON = {}));
  43319. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43320. "use strict";
  43321. var BABYLON;
  43322. (function (BABYLON) {
  43323. /**
  43324. * The PBR material of BJS following the specular glossiness convention.
  43325. *
  43326. * This fits to the PBR convention in the GLTF definition:
  43327. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43328. */
  43329. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43330. __extends(PBRSpecularGlossinessMaterial, _super);
  43331. /**
  43332. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43333. *
  43334. * @param name The material name
  43335. * @param scene The scene the material will be use in.
  43336. */
  43337. function PBRSpecularGlossinessMaterial(name, scene) {
  43338. var _this = _super.call(this, name, scene) || this;
  43339. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43340. return _this;
  43341. }
  43342. /**
  43343. * Return the currrent class name of the material.
  43344. */
  43345. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43346. return "PBRSpecularGlossinessMaterial";
  43347. };
  43348. /**
  43349. * Return the active textures of the material.
  43350. */
  43351. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43352. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43353. if (this.diffuseTexture) {
  43354. activeTextures.push(this.diffuseTexture);
  43355. }
  43356. if (this.specularGlossinessTexture) {
  43357. activeTextures.push(this.specularGlossinessTexture);
  43358. }
  43359. return activeTextures;
  43360. };
  43361. /**
  43362. * Checks to see if a texture is used in the material.
  43363. * @param texture - Base texture to use.
  43364. * @returns - Boolean specifying if a texture is used in the material.
  43365. */
  43366. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43367. if (_super.prototype.hasTexture.call(this, texture)) {
  43368. return true;
  43369. }
  43370. if (this.diffuseTexture === texture) {
  43371. return true;
  43372. }
  43373. if (this.specularGlossinessTexture === texture) {
  43374. return true;
  43375. }
  43376. return false;
  43377. };
  43378. /**
  43379. * Makes a duplicate of the current material.
  43380. * @param name - name to use for the new material.
  43381. */
  43382. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43383. var _this = this;
  43384. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43385. clone.id = name;
  43386. clone.name = name;
  43387. return clone;
  43388. };
  43389. /**
  43390. * Serialize the material to a parsable JSON object.
  43391. */
  43392. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43393. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43394. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43395. return serializationObject;
  43396. };
  43397. /**
  43398. * Parses a JSON object correponding to the serialize function.
  43399. */
  43400. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43401. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43402. };
  43403. __decorate([
  43404. BABYLON.serializeAsColor3("diffuse"),
  43405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43406. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43407. __decorate([
  43408. BABYLON.serializeAsTexture(),
  43409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43410. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43411. __decorate([
  43412. BABYLON.serializeAsColor3("specular"),
  43413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43414. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43415. __decorate([
  43416. BABYLON.serialize(),
  43417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43418. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43419. __decorate([
  43420. BABYLON.serializeAsTexture(),
  43421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43422. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43423. return PBRSpecularGlossinessMaterial;
  43424. }(BABYLON.PBRBaseSimpleMaterial));
  43425. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43426. })(BABYLON || (BABYLON = {}));
  43427. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43428. "use strict";
  43429. var BABYLON;
  43430. (function (BABYLON) {
  43431. BABYLON.CameraInputTypes = {};
  43432. var CameraInputsManager = /** @class */ (function () {
  43433. function CameraInputsManager(camera) {
  43434. this.attached = {};
  43435. this.camera = camera;
  43436. this.checkInputs = function () { };
  43437. }
  43438. /**
  43439. * Add an input method to a camera.
  43440. * builtin inputs example: camera.inputs.addGamepad();
  43441. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43442. * @param input camera input method
  43443. */
  43444. CameraInputsManager.prototype.add = function (input) {
  43445. var type = input.getSimpleName();
  43446. if (this.attached[type]) {
  43447. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43448. return;
  43449. }
  43450. this.attached[type] = input;
  43451. input.camera = this.camera;
  43452. //for checkInputs, we are dynamically creating a function
  43453. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43454. if (input.checkInputs) {
  43455. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43456. }
  43457. if (this.attachedElement) {
  43458. input.attachControl(this.attachedElement);
  43459. }
  43460. };
  43461. /**
  43462. * Remove a specific input method from a camera
  43463. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43464. * @param inputToRemove camera input method
  43465. */
  43466. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43467. for (var cam in this.attached) {
  43468. var input = this.attached[cam];
  43469. if (input === inputToRemove) {
  43470. input.detachControl(this.attachedElement);
  43471. input.camera = null;
  43472. delete this.attached[cam];
  43473. this.rebuildInputCheck();
  43474. }
  43475. }
  43476. };
  43477. CameraInputsManager.prototype.removeByType = function (inputType) {
  43478. for (var cam in this.attached) {
  43479. var input = this.attached[cam];
  43480. if (input.getClassName() === inputType) {
  43481. input.detachControl(this.attachedElement);
  43482. input.camera = null;
  43483. delete this.attached[cam];
  43484. this.rebuildInputCheck();
  43485. }
  43486. }
  43487. };
  43488. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43489. var current = this.checkInputs;
  43490. return function () {
  43491. current();
  43492. fn();
  43493. };
  43494. };
  43495. CameraInputsManager.prototype.attachInput = function (input) {
  43496. if (this.attachedElement) {
  43497. input.attachControl(this.attachedElement, this.noPreventDefault);
  43498. }
  43499. };
  43500. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43501. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43502. if (this.attachedElement) {
  43503. return;
  43504. }
  43505. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43506. this.attachedElement = element;
  43507. this.noPreventDefault = noPreventDefault;
  43508. for (var cam in this.attached) {
  43509. this.attached[cam].attachControl(element, noPreventDefault);
  43510. }
  43511. };
  43512. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43513. if (disconnect === void 0) { disconnect = false; }
  43514. if (this.attachedElement !== element) {
  43515. return;
  43516. }
  43517. for (var cam in this.attached) {
  43518. this.attached[cam].detachControl(element);
  43519. if (disconnect) {
  43520. this.attached[cam].camera = null;
  43521. }
  43522. }
  43523. this.attachedElement = null;
  43524. };
  43525. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43526. this.checkInputs = function () { };
  43527. for (var cam in this.attached) {
  43528. var input = this.attached[cam];
  43529. if (input.checkInputs) {
  43530. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43531. }
  43532. }
  43533. };
  43534. /**
  43535. * Remove all attached input methods from a camera
  43536. */
  43537. CameraInputsManager.prototype.clear = function () {
  43538. if (this.attachedElement) {
  43539. this.detachElement(this.attachedElement, true);
  43540. }
  43541. this.attached = {};
  43542. this.attachedElement = null;
  43543. this.checkInputs = function () { };
  43544. };
  43545. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43546. var inputs = {};
  43547. for (var cam in this.attached) {
  43548. var input = this.attached[cam];
  43549. var res = BABYLON.SerializationHelper.Serialize(input);
  43550. inputs[input.getClassName()] = res;
  43551. }
  43552. serializedCamera.inputsmgr = inputs;
  43553. };
  43554. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43555. var parsedInputs = parsedCamera.inputsmgr;
  43556. if (parsedInputs) {
  43557. this.clear();
  43558. for (var n in parsedInputs) {
  43559. var construct = BABYLON.CameraInputTypes[n];
  43560. if (construct) {
  43561. var parsedinput = parsedInputs[n];
  43562. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43563. this.add(input);
  43564. }
  43565. }
  43566. }
  43567. else {
  43568. //2016-03-08 this part is for managing backward compatibility
  43569. for (var n in this.attached) {
  43570. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43571. if (construct) {
  43572. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43573. this.remove(this.attached[n]);
  43574. this.add(input);
  43575. }
  43576. }
  43577. }
  43578. };
  43579. return CameraInputsManager;
  43580. }());
  43581. BABYLON.CameraInputsManager = CameraInputsManager;
  43582. })(BABYLON || (BABYLON = {}));
  43583. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43584. "use strict";
  43585. var BABYLON;
  43586. (function (BABYLON) {
  43587. var TargetCamera = /** @class */ (function (_super) {
  43588. __extends(TargetCamera, _super);
  43589. function TargetCamera(name, position, scene) {
  43590. var _this = _super.call(this, name, position, scene) || this;
  43591. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43592. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43593. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43594. _this.speed = 2.0;
  43595. _this.noRotationConstraint = false;
  43596. _this.lockedTarget = null;
  43597. _this._currentTarget = BABYLON.Vector3.Zero();
  43598. _this._viewMatrix = BABYLON.Matrix.Zero();
  43599. _this._camMatrix = BABYLON.Matrix.Zero();
  43600. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43601. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43602. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43603. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43604. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43605. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43606. _this._tempMatrix = BABYLON.Matrix.Zero();
  43607. return _this;
  43608. }
  43609. TargetCamera.prototype.getFrontPosition = function (distance) {
  43610. this.getWorldMatrix();
  43611. var direction = this.getTarget().subtract(this.position);
  43612. direction.normalize();
  43613. direction.scaleInPlace(distance);
  43614. return this.globalPosition.add(direction);
  43615. };
  43616. TargetCamera.prototype._getLockedTargetPosition = function () {
  43617. if (!this.lockedTarget) {
  43618. return null;
  43619. }
  43620. if (this.lockedTarget.absolutePosition) {
  43621. this.lockedTarget.computeWorldMatrix();
  43622. }
  43623. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43624. };
  43625. TargetCamera.prototype.storeState = function () {
  43626. this._storedPosition = this.position.clone();
  43627. this._storedRotation = this.rotation.clone();
  43628. if (this.rotationQuaternion) {
  43629. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43630. }
  43631. return _super.prototype.storeState.call(this);
  43632. };
  43633. /**
  43634. * Restored camera state. You must call storeState() first
  43635. */
  43636. TargetCamera.prototype._restoreStateValues = function () {
  43637. if (!_super.prototype._restoreStateValues.call(this)) {
  43638. return false;
  43639. }
  43640. this.position = this._storedPosition.clone();
  43641. this.rotation = this._storedRotation.clone();
  43642. if (this.rotationQuaternion) {
  43643. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43644. }
  43645. this.cameraDirection.copyFromFloats(0, 0, 0);
  43646. this.cameraRotation.copyFromFloats(0, 0);
  43647. return true;
  43648. };
  43649. // Cache
  43650. TargetCamera.prototype._initCache = function () {
  43651. _super.prototype._initCache.call(this);
  43652. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43653. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43654. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43655. };
  43656. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43657. if (!ignoreParentClass) {
  43658. _super.prototype._updateCache.call(this);
  43659. }
  43660. var lockedTargetPosition = this._getLockedTargetPosition();
  43661. if (!lockedTargetPosition) {
  43662. this._cache.lockedTarget = null;
  43663. }
  43664. else {
  43665. if (!this._cache.lockedTarget) {
  43666. this._cache.lockedTarget = lockedTargetPosition.clone();
  43667. }
  43668. else {
  43669. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43670. }
  43671. }
  43672. this._cache.rotation.copyFrom(this.rotation);
  43673. if (this.rotationQuaternion)
  43674. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43675. };
  43676. // Synchronized
  43677. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43678. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43679. return false;
  43680. }
  43681. var lockedTargetPosition = this._getLockedTargetPosition();
  43682. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43683. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43684. };
  43685. // Methods
  43686. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43687. var engine = this.getEngine();
  43688. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43689. };
  43690. // Target
  43691. TargetCamera.prototype.setTarget = function (target) {
  43692. this.upVector.normalize();
  43693. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43694. this._camMatrix.invert();
  43695. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43696. var vDir = target.subtract(this.position);
  43697. if (vDir.x >= 0.0) {
  43698. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43699. }
  43700. else {
  43701. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43702. }
  43703. this.rotation.z = 0;
  43704. if (isNaN(this.rotation.x)) {
  43705. this.rotation.x = 0;
  43706. }
  43707. if (isNaN(this.rotation.y)) {
  43708. this.rotation.y = 0;
  43709. }
  43710. if (isNaN(this.rotation.z)) {
  43711. this.rotation.z = 0;
  43712. }
  43713. if (this.rotationQuaternion) {
  43714. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43715. }
  43716. };
  43717. /**
  43718. * Return the current target position of the camera. This value is expressed in local space.
  43719. */
  43720. TargetCamera.prototype.getTarget = function () {
  43721. return this._currentTarget;
  43722. };
  43723. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43724. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43725. };
  43726. TargetCamera.prototype._updatePosition = function () {
  43727. if (this.parent) {
  43728. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43729. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43730. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43731. return;
  43732. }
  43733. this.position.addInPlace(this.cameraDirection);
  43734. };
  43735. TargetCamera.prototype._checkInputs = function () {
  43736. var needToMove = this._decideIfNeedsToMove();
  43737. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43738. // Move
  43739. if (needToMove) {
  43740. this._updatePosition();
  43741. }
  43742. // Rotate
  43743. if (needToRotate) {
  43744. this.rotation.x += this.cameraRotation.x;
  43745. this.rotation.y += this.cameraRotation.y;
  43746. //rotate, if quaternion is set and rotation was used
  43747. if (this.rotationQuaternion) {
  43748. var len = this.rotation.lengthSquared();
  43749. if (len) {
  43750. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43751. }
  43752. }
  43753. if (!this.noRotationConstraint) {
  43754. var limit = (Math.PI / 2) * 0.95;
  43755. if (this.rotation.x > limit)
  43756. this.rotation.x = limit;
  43757. if (this.rotation.x < -limit)
  43758. this.rotation.x = -limit;
  43759. }
  43760. }
  43761. // Inertia
  43762. if (needToMove) {
  43763. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43764. this.cameraDirection.x = 0;
  43765. }
  43766. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43767. this.cameraDirection.y = 0;
  43768. }
  43769. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43770. this.cameraDirection.z = 0;
  43771. }
  43772. this.cameraDirection.scaleInPlace(this.inertia);
  43773. }
  43774. if (needToRotate) {
  43775. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43776. this.cameraRotation.x = 0;
  43777. }
  43778. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43779. this.cameraRotation.y = 0;
  43780. }
  43781. this.cameraRotation.scaleInPlace(this.inertia);
  43782. }
  43783. _super.prototype._checkInputs.call(this);
  43784. };
  43785. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43786. if (this.rotationQuaternion) {
  43787. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43788. }
  43789. else {
  43790. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43791. }
  43792. //update the up vector!
  43793. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43794. };
  43795. TargetCamera.prototype._getViewMatrix = function () {
  43796. if (this.lockedTarget) {
  43797. this.setTarget(this._getLockedTargetPosition());
  43798. }
  43799. // Compute
  43800. this._updateCameraRotationMatrix();
  43801. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43802. // Computing target and final matrix
  43803. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43804. if (this.getScene().useRightHandedSystem) {
  43805. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43806. }
  43807. else {
  43808. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43809. }
  43810. return this._viewMatrix;
  43811. };
  43812. /**
  43813. * @override
  43814. * Override Camera.createRigCamera
  43815. */
  43816. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43817. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43818. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43819. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43820. if (!this.rotationQuaternion) {
  43821. this.rotationQuaternion = new BABYLON.Quaternion();
  43822. }
  43823. rigCamera._cameraRigParams = {};
  43824. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43825. }
  43826. return rigCamera;
  43827. }
  43828. return null;
  43829. };
  43830. /**
  43831. * @override
  43832. * Override Camera._updateRigCameras
  43833. */
  43834. TargetCamera.prototype._updateRigCameras = function () {
  43835. var camLeft = this._rigCameras[0];
  43836. var camRight = this._rigCameras[1];
  43837. switch (this.cameraRigMode) {
  43838. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43839. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43840. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43841. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43842. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43843. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43844. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43845. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43846. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43847. camLeft.setTarget(this.getTarget());
  43848. camRight.setTarget(this.getTarget());
  43849. break;
  43850. case BABYLON.Camera.RIG_MODE_VR:
  43851. if (camLeft.rotationQuaternion) {
  43852. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43853. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43854. }
  43855. else {
  43856. camLeft.rotation.copyFrom(this.rotation);
  43857. camRight.rotation.copyFrom(this.rotation);
  43858. }
  43859. camLeft.position.copyFrom(this.position);
  43860. camRight.position.copyFrom(this.position);
  43861. break;
  43862. }
  43863. _super.prototype._updateRigCameras.call(this);
  43864. };
  43865. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43866. if (!this._rigCamTransformMatrix) {
  43867. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43868. }
  43869. var target = this.getTarget();
  43870. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43871. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43872. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43873. };
  43874. TargetCamera.prototype.getClassName = function () {
  43875. return "TargetCamera";
  43876. };
  43877. __decorate([
  43878. BABYLON.serializeAsVector3()
  43879. ], TargetCamera.prototype, "rotation", void 0);
  43880. __decorate([
  43881. BABYLON.serialize()
  43882. ], TargetCamera.prototype, "speed", void 0);
  43883. __decorate([
  43884. BABYLON.serializeAsMeshReference("lockedTargetId")
  43885. ], TargetCamera.prototype, "lockedTarget", void 0);
  43886. return TargetCamera;
  43887. }(BABYLON.Camera));
  43888. BABYLON.TargetCamera = TargetCamera;
  43889. })(BABYLON || (BABYLON = {}));
  43890. //# sourceMappingURL=babylon.targetCamera.js.map
  43891. "use strict";
  43892. var BABYLON;
  43893. (function (BABYLON) {
  43894. var FreeCameraMouseInput = /** @class */ (function () {
  43895. function FreeCameraMouseInput(touchEnabled) {
  43896. if (touchEnabled === void 0) { touchEnabled = true; }
  43897. this.touchEnabled = touchEnabled;
  43898. this.buttons = [0, 1, 2];
  43899. this.angularSensibility = 2000.0;
  43900. this.previousPosition = null;
  43901. }
  43902. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43903. var _this = this;
  43904. var engine = this.camera.getEngine();
  43905. if (!this._pointerInput) {
  43906. this._pointerInput = function (p, s) {
  43907. var evt = p.event;
  43908. if (engine.isInVRExclusivePointerMode) {
  43909. return;
  43910. }
  43911. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43912. return;
  43913. }
  43914. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43915. return;
  43916. }
  43917. var srcElement = (evt.srcElement || evt.target);
  43918. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43919. try {
  43920. srcElement.setPointerCapture(evt.pointerId);
  43921. }
  43922. catch (e) {
  43923. //Nothing to do with the error. Execution will continue.
  43924. }
  43925. _this.previousPosition = {
  43926. x: evt.clientX,
  43927. y: evt.clientY
  43928. };
  43929. if (!noPreventDefault) {
  43930. evt.preventDefault();
  43931. element.focus();
  43932. }
  43933. }
  43934. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43935. try {
  43936. srcElement.releasePointerCapture(evt.pointerId);
  43937. }
  43938. catch (e) {
  43939. //Nothing to do with the error.
  43940. }
  43941. _this.previousPosition = null;
  43942. if (!noPreventDefault) {
  43943. evt.preventDefault();
  43944. }
  43945. }
  43946. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43947. if (!_this.previousPosition || engine.isPointerLock) {
  43948. return;
  43949. }
  43950. var offsetX = evt.clientX - _this.previousPosition.x;
  43951. var offsetY = evt.clientY - _this.previousPosition.y;
  43952. if (_this.camera.getScene().useRightHandedSystem) {
  43953. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43954. }
  43955. else {
  43956. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43957. }
  43958. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43959. _this.previousPosition = {
  43960. x: evt.clientX,
  43961. y: evt.clientY
  43962. };
  43963. if (!noPreventDefault) {
  43964. evt.preventDefault();
  43965. }
  43966. }
  43967. };
  43968. }
  43969. this._onMouseMove = function (evt) {
  43970. if (!engine.isPointerLock) {
  43971. return;
  43972. }
  43973. if (engine.isInVRExclusivePointerMode) {
  43974. return;
  43975. }
  43976. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43977. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43978. if (_this.camera.getScene().useRightHandedSystem) {
  43979. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43980. }
  43981. else {
  43982. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43983. }
  43984. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43985. _this.previousPosition = null;
  43986. if (!noPreventDefault) {
  43987. evt.preventDefault();
  43988. }
  43989. };
  43990. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43991. element.addEventListener("mousemove", this._onMouseMove, false);
  43992. };
  43993. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43994. if (this._observer && element) {
  43995. this.camera.getScene().onPointerObservable.remove(this._observer);
  43996. if (this._onMouseMove) {
  43997. element.removeEventListener("mousemove", this._onMouseMove);
  43998. }
  43999. this._observer = null;
  44000. this._onMouseMove = null;
  44001. this.previousPosition = null;
  44002. }
  44003. };
  44004. FreeCameraMouseInput.prototype.getClassName = function () {
  44005. return "FreeCameraMouseInput";
  44006. };
  44007. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44008. return "mouse";
  44009. };
  44010. __decorate([
  44011. BABYLON.serialize()
  44012. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44013. __decorate([
  44014. BABYLON.serialize()
  44015. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44016. return FreeCameraMouseInput;
  44017. }());
  44018. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44019. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44020. })(BABYLON || (BABYLON = {}));
  44021. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44022. "use strict";
  44023. var BABYLON;
  44024. (function (BABYLON) {
  44025. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44026. function FreeCameraKeyboardMoveInput() {
  44027. this._keys = new Array();
  44028. this.keysUp = [38];
  44029. this.keysDown = [40];
  44030. this.keysLeft = [37];
  44031. this.keysRight = [39];
  44032. }
  44033. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44034. var _this = this;
  44035. if (this._onCanvasBlurObserver) {
  44036. return;
  44037. }
  44038. this._scene = this.camera.getScene();
  44039. this._engine = this._scene.getEngine();
  44040. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44041. _this._keys = [];
  44042. });
  44043. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44044. var evt = info.event;
  44045. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44046. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44047. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44048. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44049. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44050. var index = _this._keys.indexOf(evt.keyCode);
  44051. if (index === -1) {
  44052. _this._keys.push(evt.keyCode);
  44053. }
  44054. if (!noPreventDefault) {
  44055. evt.preventDefault();
  44056. }
  44057. }
  44058. }
  44059. else {
  44060. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44061. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44062. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44063. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44064. var index = _this._keys.indexOf(evt.keyCode);
  44065. if (index >= 0) {
  44066. _this._keys.splice(index, 1);
  44067. }
  44068. if (!noPreventDefault) {
  44069. evt.preventDefault();
  44070. }
  44071. }
  44072. }
  44073. });
  44074. };
  44075. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44076. if (this._scene) {
  44077. if (this._onKeyboardObserver) {
  44078. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44079. }
  44080. if (this._onCanvasBlurObserver) {
  44081. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44082. }
  44083. this._onKeyboardObserver = null;
  44084. this._onCanvasBlurObserver = null;
  44085. }
  44086. this._keys = [];
  44087. };
  44088. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44089. if (this._onKeyboardObserver) {
  44090. var camera = this.camera;
  44091. // Keyboard
  44092. for (var index = 0; index < this._keys.length; index++) {
  44093. var keyCode = this._keys[index];
  44094. var speed = camera._computeLocalCameraSpeed();
  44095. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44096. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44097. }
  44098. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44099. camera._localDirection.copyFromFloats(0, 0, speed);
  44100. }
  44101. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44102. camera._localDirection.copyFromFloats(speed, 0, 0);
  44103. }
  44104. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44105. camera._localDirection.copyFromFloats(0, 0, -speed);
  44106. }
  44107. if (camera.getScene().useRightHandedSystem) {
  44108. camera._localDirection.z *= -1;
  44109. }
  44110. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44111. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44112. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44113. }
  44114. }
  44115. };
  44116. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44117. return "FreeCameraKeyboardMoveInput";
  44118. };
  44119. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44120. this._keys = [];
  44121. };
  44122. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44123. return "keyboard";
  44124. };
  44125. __decorate([
  44126. BABYLON.serialize()
  44127. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44128. __decorate([
  44129. BABYLON.serialize()
  44130. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44131. __decorate([
  44132. BABYLON.serialize()
  44133. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44134. __decorate([
  44135. BABYLON.serialize()
  44136. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44137. return FreeCameraKeyboardMoveInput;
  44138. }());
  44139. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44140. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44141. })(BABYLON || (BABYLON = {}));
  44142. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44143. "use strict";
  44144. var BABYLON;
  44145. (function (BABYLON) {
  44146. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44147. __extends(FreeCameraInputsManager, _super);
  44148. function FreeCameraInputsManager(camera) {
  44149. return _super.call(this, camera) || this;
  44150. }
  44151. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44152. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44153. return this;
  44154. };
  44155. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44156. if (touchEnabled === void 0) { touchEnabled = true; }
  44157. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44158. return this;
  44159. };
  44160. FreeCameraInputsManager.prototype.addGamepad = function () {
  44161. this.add(new BABYLON.FreeCameraGamepadInput());
  44162. return this;
  44163. };
  44164. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44165. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44166. return this;
  44167. };
  44168. FreeCameraInputsManager.prototype.addTouch = function () {
  44169. this.add(new BABYLON.FreeCameraTouchInput());
  44170. return this;
  44171. };
  44172. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44173. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44174. return this;
  44175. };
  44176. return FreeCameraInputsManager;
  44177. }(BABYLON.CameraInputsManager));
  44178. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44179. })(BABYLON || (BABYLON = {}));
  44180. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44181. "use strict";
  44182. var BABYLON;
  44183. (function (BABYLON) {
  44184. var FreeCamera = /** @class */ (function (_super) {
  44185. __extends(FreeCamera, _super);
  44186. function FreeCamera(name, position, scene) {
  44187. var _this = _super.call(this, name, position, scene) || this;
  44188. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44189. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44190. _this.checkCollisions = false;
  44191. _this.applyGravity = false;
  44192. _this._needMoveForGravity = false;
  44193. _this._oldPosition = BABYLON.Vector3.Zero();
  44194. _this._diffPosition = BABYLON.Vector3.Zero();
  44195. _this._newPosition = BABYLON.Vector3.Zero();
  44196. // Collisions
  44197. _this._collisionMask = -1;
  44198. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44199. if (collidedMesh === void 0) { collidedMesh = null; }
  44200. //TODO move this to the collision coordinator!
  44201. if (_this.getScene().workerCollisions)
  44202. newPosition.multiplyInPlace(_this._collider._radius);
  44203. var updatePosition = function (newPos) {
  44204. _this._newPosition.copyFrom(newPos);
  44205. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44206. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44207. _this.position.addInPlace(_this._diffPosition);
  44208. if (_this.onCollide && collidedMesh) {
  44209. _this.onCollide(collidedMesh);
  44210. }
  44211. }
  44212. };
  44213. updatePosition(newPosition);
  44214. };
  44215. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44216. _this.inputs.addKeyboard().addMouse();
  44217. return _this;
  44218. }
  44219. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44220. //-- begin properties for backward compatibility for inputs
  44221. /**
  44222. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44223. * Higher values reduce sensitivity.
  44224. */
  44225. get: function () {
  44226. var mouse = this.inputs.attached["mouse"];
  44227. if (mouse)
  44228. return mouse.angularSensibility;
  44229. return 0;
  44230. },
  44231. /**
  44232. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44233. * Higher values reduce sensitivity.
  44234. */
  44235. set: function (value) {
  44236. var mouse = this.inputs.attached["mouse"];
  44237. if (mouse)
  44238. mouse.angularSensibility = value;
  44239. },
  44240. enumerable: true,
  44241. configurable: true
  44242. });
  44243. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44244. get: function () {
  44245. var keyboard = this.inputs.attached["keyboard"];
  44246. if (keyboard)
  44247. return keyboard.keysUp;
  44248. return [];
  44249. },
  44250. set: function (value) {
  44251. var keyboard = this.inputs.attached["keyboard"];
  44252. if (keyboard)
  44253. keyboard.keysUp = value;
  44254. },
  44255. enumerable: true,
  44256. configurable: true
  44257. });
  44258. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44259. get: function () {
  44260. var keyboard = this.inputs.attached["keyboard"];
  44261. if (keyboard)
  44262. return keyboard.keysDown;
  44263. return [];
  44264. },
  44265. set: function (value) {
  44266. var keyboard = this.inputs.attached["keyboard"];
  44267. if (keyboard)
  44268. keyboard.keysDown = value;
  44269. },
  44270. enumerable: true,
  44271. configurable: true
  44272. });
  44273. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44274. get: function () {
  44275. var keyboard = this.inputs.attached["keyboard"];
  44276. if (keyboard)
  44277. return keyboard.keysLeft;
  44278. return [];
  44279. },
  44280. set: function (value) {
  44281. var keyboard = this.inputs.attached["keyboard"];
  44282. if (keyboard)
  44283. keyboard.keysLeft = value;
  44284. },
  44285. enumerable: true,
  44286. configurable: true
  44287. });
  44288. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44289. get: function () {
  44290. var keyboard = this.inputs.attached["keyboard"];
  44291. if (keyboard)
  44292. return keyboard.keysRight;
  44293. return [];
  44294. },
  44295. set: function (value) {
  44296. var keyboard = this.inputs.attached["keyboard"];
  44297. if (keyboard)
  44298. keyboard.keysRight = value;
  44299. },
  44300. enumerable: true,
  44301. configurable: true
  44302. });
  44303. // Controls
  44304. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44305. this.inputs.attachElement(element, noPreventDefault);
  44306. };
  44307. FreeCamera.prototype.detachControl = function (element) {
  44308. this.inputs.detachElement(element);
  44309. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44310. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44311. };
  44312. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44313. get: function () {
  44314. return this._collisionMask;
  44315. },
  44316. set: function (mask) {
  44317. this._collisionMask = !isNaN(mask) ? mask : -1;
  44318. },
  44319. enumerable: true,
  44320. configurable: true
  44321. });
  44322. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44323. var globalPosition;
  44324. if (this.parent) {
  44325. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44326. }
  44327. else {
  44328. globalPosition = this.position;
  44329. }
  44330. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44331. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44332. if (!this._collider) {
  44333. this._collider = new BABYLON.Collider();
  44334. }
  44335. this._collider._radius = this.ellipsoid;
  44336. this._collider.collisionMask = this._collisionMask;
  44337. //no need for clone, as long as gravity is not on.
  44338. var actualDisplacement = displacement;
  44339. //add gravity to the direction to prevent the dual-collision checking
  44340. if (this.applyGravity) {
  44341. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44342. actualDisplacement = displacement.add(this.getScene().gravity);
  44343. }
  44344. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44345. };
  44346. FreeCamera.prototype._checkInputs = function () {
  44347. if (!this._localDirection) {
  44348. this._localDirection = BABYLON.Vector3.Zero();
  44349. this._transformedDirection = BABYLON.Vector3.Zero();
  44350. }
  44351. this.inputs.checkInputs();
  44352. _super.prototype._checkInputs.call(this);
  44353. };
  44354. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44355. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44356. };
  44357. FreeCamera.prototype._updatePosition = function () {
  44358. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44359. this._collideWithWorld(this.cameraDirection);
  44360. }
  44361. else {
  44362. _super.prototype._updatePosition.call(this);
  44363. }
  44364. };
  44365. FreeCamera.prototype.dispose = function () {
  44366. this.inputs.clear();
  44367. _super.prototype.dispose.call(this);
  44368. };
  44369. FreeCamera.prototype.getClassName = function () {
  44370. return "FreeCamera";
  44371. };
  44372. __decorate([
  44373. BABYLON.serializeAsVector3()
  44374. ], FreeCamera.prototype, "ellipsoid", void 0);
  44375. __decorate([
  44376. BABYLON.serializeAsVector3()
  44377. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44378. __decorate([
  44379. BABYLON.serialize()
  44380. ], FreeCamera.prototype, "checkCollisions", void 0);
  44381. __decorate([
  44382. BABYLON.serialize()
  44383. ], FreeCamera.prototype, "applyGravity", void 0);
  44384. return FreeCamera;
  44385. }(BABYLON.TargetCamera));
  44386. BABYLON.FreeCamera = FreeCamera;
  44387. })(BABYLON || (BABYLON = {}));
  44388. //# sourceMappingURL=babylon.freeCamera.js.map
  44389. "use strict";
  44390. var BABYLON;
  44391. (function (BABYLON) {
  44392. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44393. function ArcRotateCameraKeyboardMoveInput() {
  44394. this._keys = new Array();
  44395. this.keysUp = [38];
  44396. this.keysDown = [40];
  44397. this.keysLeft = [37];
  44398. this.keysRight = [39];
  44399. this.keysReset = [220];
  44400. this.panningSensibility = 50.0;
  44401. this.zoomingSensibility = 25.0;
  44402. this.useAltToZoom = true;
  44403. }
  44404. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44405. var _this = this;
  44406. if (this._onCanvasBlurObserver) {
  44407. return;
  44408. }
  44409. this._scene = this.camera.getScene();
  44410. this._engine = this._scene.getEngine();
  44411. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44412. _this._keys = [];
  44413. });
  44414. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44415. var evt = info.event;
  44416. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44417. _this._ctrlPressed = evt.ctrlKey;
  44418. _this._altPressed = evt.altKey;
  44419. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44420. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44421. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44422. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44423. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44424. var index = _this._keys.indexOf(evt.keyCode);
  44425. if (index === -1) {
  44426. _this._keys.push(evt.keyCode);
  44427. }
  44428. if (evt.preventDefault) {
  44429. if (!noPreventDefault) {
  44430. evt.preventDefault();
  44431. }
  44432. }
  44433. }
  44434. }
  44435. else {
  44436. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44437. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44438. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44439. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44440. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44441. var index = _this._keys.indexOf(evt.keyCode);
  44442. if (index >= 0) {
  44443. _this._keys.splice(index, 1);
  44444. }
  44445. if (evt.preventDefault) {
  44446. if (!noPreventDefault) {
  44447. evt.preventDefault();
  44448. }
  44449. }
  44450. }
  44451. }
  44452. });
  44453. };
  44454. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44455. if (this._scene) {
  44456. if (this._onKeyboardObserver) {
  44457. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44458. }
  44459. if (this._onCanvasBlurObserver) {
  44460. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44461. }
  44462. this._onKeyboardObserver = null;
  44463. this._onCanvasBlurObserver = null;
  44464. }
  44465. this._keys = [];
  44466. };
  44467. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44468. if (this._onKeyboardObserver) {
  44469. var camera = this.camera;
  44470. for (var index = 0; index < this._keys.length; index++) {
  44471. var keyCode = this._keys[index];
  44472. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44473. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44474. camera.inertialPanningX -= 1 / this.panningSensibility;
  44475. }
  44476. else {
  44477. camera.inertialAlphaOffset -= 0.01;
  44478. }
  44479. }
  44480. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44481. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44482. camera.inertialPanningY += 1 / this.panningSensibility;
  44483. }
  44484. else if (this._altPressed && this.useAltToZoom) {
  44485. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44486. }
  44487. else {
  44488. camera.inertialBetaOffset -= 0.01;
  44489. }
  44490. }
  44491. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44492. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44493. camera.inertialPanningX += 1 / this.panningSensibility;
  44494. }
  44495. else {
  44496. camera.inertialAlphaOffset += 0.01;
  44497. }
  44498. }
  44499. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44500. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44501. camera.inertialPanningY -= 1 / this.panningSensibility;
  44502. }
  44503. else if (this._altPressed && this.useAltToZoom) {
  44504. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44505. }
  44506. else {
  44507. camera.inertialBetaOffset += 0.01;
  44508. }
  44509. }
  44510. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44511. camera.restoreState();
  44512. }
  44513. }
  44514. }
  44515. };
  44516. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44517. return "ArcRotateCameraKeyboardMoveInput";
  44518. };
  44519. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44520. return "keyboard";
  44521. };
  44522. __decorate([
  44523. BABYLON.serialize()
  44524. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44525. __decorate([
  44526. BABYLON.serialize()
  44527. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44528. __decorate([
  44529. BABYLON.serialize()
  44530. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44531. __decorate([
  44532. BABYLON.serialize()
  44533. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44534. __decorate([
  44535. BABYLON.serialize()
  44536. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44537. __decorate([
  44538. BABYLON.serialize()
  44539. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44540. __decorate([
  44541. BABYLON.serialize()
  44542. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44543. __decorate([
  44544. BABYLON.serialize()
  44545. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44546. return ArcRotateCameraKeyboardMoveInput;
  44547. }());
  44548. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44549. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44550. })(BABYLON || (BABYLON = {}));
  44551. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44552. "use strict";
  44553. var BABYLON;
  44554. (function (BABYLON) {
  44555. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44556. function ArcRotateCameraMouseWheelInput() {
  44557. this.wheelPrecision = 3.0;
  44558. /**
  44559. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44560. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44561. */
  44562. this.wheelDeltaPercentage = 0;
  44563. }
  44564. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44565. var _this = this;
  44566. this._wheel = function (p, s) {
  44567. //sanity check - this should be a PointerWheel event.
  44568. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44569. return;
  44570. var event = p.event;
  44571. var delta = 0;
  44572. if (event.wheelDelta) {
  44573. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44574. }
  44575. else if (event.detail) {
  44576. delta = -event.detail / _this.wheelPrecision;
  44577. }
  44578. if (delta)
  44579. _this.camera.inertialRadiusOffset += delta;
  44580. if (event.preventDefault) {
  44581. if (!noPreventDefault) {
  44582. event.preventDefault();
  44583. }
  44584. }
  44585. };
  44586. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44587. };
  44588. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44589. if (this._observer && element) {
  44590. this.camera.getScene().onPointerObservable.remove(this._observer);
  44591. this._observer = null;
  44592. this._wheel = null;
  44593. }
  44594. };
  44595. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44596. return "ArcRotateCameraMouseWheelInput";
  44597. };
  44598. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44599. return "mousewheel";
  44600. };
  44601. __decorate([
  44602. BABYLON.serialize()
  44603. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44604. __decorate([
  44605. BABYLON.serialize()
  44606. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44607. return ArcRotateCameraMouseWheelInput;
  44608. }());
  44609. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44610. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44611. })(BABYLON || (BABYLON = {}));
  44612. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44613. "use strict";
  44614. var BABYLON;
  44615. (function (BABYLON) {
  44616. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44617. function ArcRotateCameraPointersInput() {
  44618. this.buttons = [0, 1, 2];
  44619. this.angularSensibilityX = 1000.0;
  44620. this.angularSensibilityY = 1000.0;
  44621. this.pinchPrecision = 12.0;
  44622. /**
  44623. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44624. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44625. */
  44626. this.pinchDeltaPercentage = 0;
  44627. this.panningSensibility = 1000.0;
  44628. this.multiTouchPanning = true;
  44629. this.multiTouchPanAndZoom = true;
  44630. this._isPanClick = false;
  44631. this.pinchInwards = true;
  44632. }
  44633. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44634. var _this = this;
  44635. var engine = this.camera.getEngine();
  44636. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44637. var pointA = null;
  44638. var pointB = null;
  44639. var previousPinchSquaredDistance = 0;
  44640. var initialDistance = 0;
  44641. var twoFingerActivityCount = 0;
  44642. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44643. this._pointerInput = function (p, s) {
  44644. var evt = p.event;
  44645. var isTouch = p.event.pointerType === "touch";
  44646. if (engine.isInVRExclusivePointerMode) {
  44647. return;
  44648. }
  44649. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44650. return;
  44651. }
  44652. var srcElement = (evt.srcElement || evt.target);
  44653. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44654. try {
  44655. srcElement.setPointerCapture(evt.pointerId);
  44656. }
  44657. catch (e) {
  44658. //Nothing to do with the error. Execution will continue.
  44659. }
  44660. // Manage panning with pan button click
  44661. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44662. // manage pointers
  44663. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44664. if (pointA === null) {
  44665. pointA = cacheSoloPointer;
  44666. }
  44667. else if (pointB === null) {
  44668. pointB = cacheSoloPointer;
  44669. }
  44670. if (!noPreventDefault) {
  44671. evt.preventDefault();
  44672. element.focus();
  44673. }
  44674. }
  44675. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44676. _this.camera.restoreState();
  44677. }
  44678. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44679. try {
  44680. srcElement.releasePointerCapture(evt.pointerId);
  44681. }
  44682. catch (e) {
  44683. //Nothing to do with the error.
  44684. }
  44685. cacheSoloPointer = null;
  44686. previousPinchSquaredDistance = 0;
  44687. previousMultiTouchPanPosition.isPaning = false;
  44688. previousMultiTouchPanPosition.isPinching = false;
  44689. twoFingerActivityCount = 0;
  44690. initialDistance = 0;
  44691. if (!isTouch) {
  44692. pointB = null; // Mouse and pen are mono pointer
  44693. }
  44694. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44695. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44696. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44697. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44698. if (engine.badOS) {
  44699. pointA = pointB = null;
  44700. }
  44701. else {
  44702. //only remove the impacted pointer in case of multitouch allowing on most
  44703. //platforms switching from rotate to zoom and pan seamlessly.
  44704. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44705. pointA = pointB;
  44706. pointB = null;
  44707. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44708. }
  44709. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44710. pointB = null;
  44711. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44712. }
  44713. else {
  44714. pointA = pointB = null;
  44715. }
  44716. }
  44717. if (!noPreventDefault) {
  44718. evt.preventDefault();
  44719. }
  44720. }
  44721. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44722. if (!noPreventDefault) {
  44723. evt.preventDefault();
  44724. }
  44725. // One button down
  44726. if (pointA && pointB === null && cacheSoloPointer) {
  44727. if (_this.panningSensibility !== 0 &&
  44728. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44729. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44730. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44731. }
  44732. else {
  44733. var offsetX = evt.clientX - cacheSoloPointer.x;
  44734. var offsetY = evt.clientY - cacheSoloPointer.y;
  44735. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44736. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44737. }
  44738. cacheSoloPointer.x = evt.clientX;
  44739. cacheSoloPointer.y = evt.clientY;
  44740. }
  44741. else if (pointA && pointB) {
  44742. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44743. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44744. ed.x = evt.clientX;
  44745. ed.y = evt.clientY;
  44746. var direction = _this.pinchInwards ? 1 : -1;
  44747. var distX = pointA.x - pointB.x;
  44748. var distY = pointA.y - pointB.y;
  44749. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44750. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44751. if (previousPinchSquaredDistance === 0) {
  44752. initialDistance = pinchDistance;
  44753. previousPinchSquaredDistance = pinchSquaredDistance;
  44754. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44755. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44756. return;
  44757. }
  44758. if (_this.multiTouchPanAndZoom) {
  44759. if (_this.pinchDeltaPercentage) {
  44760. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44761. }
  44762. else {
  44763. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44764. (_this.pinchPrecision *
  44765. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44766. direction);
  44767. }
  44768. if (_this.panningSensibility !== 0) {
  44769. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44770. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44771. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44772. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44773. previousMultiTouchPanPosition.x = pointersCenterX;
  44774. previousMultiTouchPanPosition.y = pointersCenterY;
  44775. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44776. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44777. }
  44778. }
  44779. else {
  44780. twoFingerActivityCount++;
  44781. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44782. if (_this.pinchDeltaPercentage) {
  44783. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44784. }
  44785. else {
  44786. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44787. (_this.pinchPrecision *
  44788. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44789. direction);
  44790. }
  44791. previousMultiTouchPanPosition.isPaning = false;
  44792. previousMultiTouchPanPosition.isPinching = true;
  44793. }
  44794. else {
  44795. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44796. if (!previousMultiTouchPanPosition.isPaning) {
  44797. previousMultiTouchPanPosition.isPaning = true;
  44798. previousMultiTouchPanPosition.isPinching = false;
  44799. previousMultiTouchPanPosition.x = ed.x;
  44800. previousMultiTouchPanPosition.y = ed.y;
  44801. return;
  44802. }
  44803. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44804. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44805. }
  44806. }
  44807. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44808. previousMultiTouchPanPosition.x = ed.x;
  44809. previousMultiTouchPanPosition.y = ed.y;
  44810. }
  44811. }
  44812. previousPinchSquaredDistance = pinchSquaredDistance;
  44813. }
  44814. }
  44815. };
  44816. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44817. this._onContextMenu = function (evt) {
  44818. evt.preventDefault();
  44819. };
  44820. if (!this.camera._useCtrlForPanning) {
  44821. element.addEventListener("contextmenu", this._onContextMenu, false);
  44822. }
  44823. this._onLostFocus = function () {
  44824. //this._keys = [];
  44825. pointA = pointB = null;
  44826. previousPinchSquaredDistance = 0;
  44827. previousMultiTouchPanPosition.isPaning = false;
  44828. previousMultiTouchPanPosition.isPinching = false;
  44829. twoFingerActivityCount = 0;
  44830. cacheSoloPointer = null;
  44831. initialDistance = 0;
  44832. };
  44833. this._onMouseMove = function (evt) {
  44834. if (!engine.isPointerLock) {
  44835. return;
  44836. }
  44837. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44838. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44839. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44840. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44841. if (!noPreventDefault) {
  44842. evt.preventDefault();
  44843. }
  44844. };
  44845. this._onGestureStart = function (e) {
  44846. if (window.MSGesture === undefined) {
  44847. return;
  44848. }
  44849. if (!_this._MSGestureHandler) {
  44850. _this._MSGestureHandler = new MSGesture();
  44851. _this._MSGestureHandler.target = element;
  44852. }
  44853. _this._MSGestureHandler.addPointer(e.pointerId);
  44854. };
  44855. this._onGesture = function (e) {
  44856. _this.camera.radius *= e.scale;
  44857. if (e.preventDefault) {
  44858. if (!noPreventDefault) {
  44859. e.stopPropagation();
  44860. e.preventDefault();
  44861. }
  44862. }
  44863. };
  44864. element.addEventListener("mousemove", this._onMouseMove, false);
  44865. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44866. element.addEventListener("MSGestureChange", this._onGesture, false);
  44867. BABYLON.Tools.RegisterTopRootEvents([
  44868. { name: "blur", handler: this._onLostFocus }
  44869. ]);
  44870. };
  44871. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44872. if (this._onLostFocus) {
  44873. BABYLON.Tools.UnregisterTopRootEvents([
  44874. { name: "blur", handler: this._onLostFocus }
  44875. ]);
  44876. }
  44877. if (element && this._observer) {
  44878. this.camera.getScene().onPointerObservable.remove(this._observer);
  44879. this._observer = null;
  44880. if (this._onContextMenu) {
  44881. element.removeEventListener("contextmenu", this._onContextMenu);
  44882. }
  44883. if (this._onMouseMove) {
  44884. element.removeEventListener("mousemove", this._onMouseMove);
  44885. }
  44886. if (this._onGestureStart) {
  44887. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44888. }
  44889. if (this._onGesture) {
  44890. element.removeEventListener("MSGestureChange", this._onGesture);
  44891. }
  44892. this._isPanClick = false;
  44893. this.pinchInwards = true;
  44894. this._onMouseMove = null;
  44895. this._onGestureStart = null;
  44896. this._onGesture = null;
  44897. this._MSGestureHandler = null;
  44898. this._onLostFocus = null;
  44899. this._onContextMenu = null;
  44900. }
  44901. };
  44902. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44903. return "ArcRotateCameraPointersInput";
  44904. };
  44905. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44906. return "pointers";
  44907. };
  44908. __decorate([
  44909. BABYLON.serialize()
  44910. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44911. __decorate([
  44912. BABYLON.serialize()
  44913. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44914. __decorate([
  44915. BABYLON.serialize()
  44916. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44917. __decorate([
  44918. BABYLON.serialize()
  44919. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44920. __decorate([
  44921. BABYLON.serialize()
  44922. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44923. __decorate([
  44924. BABYLON.serialize()
  44925. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44926. __decorate([
  44927. BABYLON.serialize()
  44928. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44929. __decorate([
  44930. BABYLON.serialize()
  44931. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44932. return ArcRotateCameraPointersInput;
  44933. }());
  44934. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44935. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44936. })(BABYLON || (BABYLON = {}));
  44937. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44938. "use strict";
  44939. var BABYLON;
  44940. (function (BABYLON) {
  44941. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44942. __extends(ArcRotateCameraInputsManager, _super);
  44943. function ArcRotateCameraInputsManager(camera) {
  44944. return _super.call(this, camera) || this;
  44945. }
  44946. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44947. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44948. return this;
  44949. };
  44950. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44951. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44952. return this;
  44953. };
  44954. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44955. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44956. return this;
  44957. };
  44958. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44959. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44960. return this;
  44961. };
  44962. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44963. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44964. return this;
  44965. };
  44966. return ArcRotateCameraInputsManager;
  44967. }(BABYLON.CameraInputsManager));
  44968. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44969. })(BABYLON || (BABYLON = {}));
  44970. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44971. "use strict";
  44972. var BABYLON;
  44973. (function (BABYLON) {
  44974. var ArcRotateCamera = /** @class */ (function (_super) {
  44975. __extends(ArcRotateCamera, _super);
  44976. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44977. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44978. _this.inertialAlphaOffset = 0;
  44979. _this.inertialBetaOffset = 0;
  44980. _this.inertialRadiusOffset = 0;
  44981. _this.lowerAlphaLimit = null;
  44982. _this.upperAlphaLimit = null;
  44983. _this.lowerBetaLimit = 0.01;
  44984. _this.upperBetaLimit = Math.PI;
  44985. _this.lowerRadiusLimit = null;
  44986. _this.upperRadiusLimit = null;
  44987. _this.inertialPanningX = 0;
  44988. _this.inertialPanningY = 0;
  44989. _this.pinchToPanMaxDistance = 20;
  44990. _this.panningDistanceLimit = null;
  44991. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44992. _this.panningInertia = 0.9;
  44993. //-- end properties for backward compatibility for inputs
  44994. _this.zoomOnFactor = 1;
  44995. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44996. _this.allowUpsideDown = true;
  44997. _this._viewMatrix = new BABYLON.Matrix();
  44998. // Panning
  44999. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45000. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45001. _this.checkCollisions = false;
  45002. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45003. _this._previousPosition = BABYLON.Vector3.Zero();
  45004. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45005. _this._newPosition = BABYLON.Vector3.Zero();
  45006. _this._computationVector = BABYLON.Vector3.Zero();
  45007. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45008. if (collidedMesh === void 0) { collidedMesh = null; }
  45009. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45010. newPosition.multiplyInPlace(_this._collider._radius);
  45011. }
  45012. if (!collidedMesh) {
  45013. _this._previousPosition.copyFrom(_this.position);
  45014. }
  45015. else {
  45016. _this.setPosition(newPosition);
  45017. if (_this.onCollide) {
  45018. _this.onCollide(collidedMesh);
  45019. }
  45020. }
  45021. // Recompute because of constraints
  45022. var cosa = Math.cos(_this.alpha);
  45023. var sina = Math.sin(_this.alpha);
  45024. var cosb = Math.cos(_this.beta);
  45025. var sinb = Math.sin(_this.beta);
  45026. if (sinb === 0) {
  45027. sinb = 0.0001;
  45028. }
  45029. var target = _this._getTargetPosition();
  45030. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45031. target.addToRef(_this._computationVector, _this._newPosition);
  45032. _this.position.copyFrom(_this._newPosition);
  45033. var up = _this.upVector;
  45034. if (_this.allowUpsideDown && _this.beta < 0) {
  45035. up = up.clone();
  45036. up = up.negate();
  45037. }
  45038. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45039. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45040. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45041. _this._collisionTriggered = false;
  45042. };
  45043. _this._target = BABYLON.Vector3.Zero();
  45044. if (target) {
  45045. _this.setTarget(target);
  45046. }
  45047. _this.alpha = alpha;
  45048. _this.beta = beta;
  45049. _this.radius = radius;
  45050. _this.getViewMatrix();
  45051. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45052. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45053. return _this;
  45054. }
  45055. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45056. get: function () {
  45057. return this._target;
  45058. },
  45059. set: function (value) {
  45060. this.setTarget(value);
  45061. },
  45062. enumerable: true,
  45063. configurable: true
  45064. });
  45065. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45066. //-- begin properties for backward compatibility for inputs
  45067. get: function () {
  45068. var pointers = this.inputs.attached["pointers"];
  45069. if (pointers)
  45070. return pointers.angularSensibilityX;
  45071. return 0;
  45072. },
  45073. set: function (value) {
  45074. var pointers = this.inputs.attached["pointers"];
  45075. if (pointers) {
  45076. pointers.angularSensibilityX = value;
  45077. }
  45078. },
  45079. enumerable: true,
  45080. configurable: true
  45081. });
  45082. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45083. get: function () {
  45084. var pointers = this.inputs.attached["pointers"];
  45085. if (pointers)
  45086. return pointers.angularSensibilityY;
  45087. return 0;
  45088. },
  45089. set: function (value) {
  45090. var pointers = this.inputs.attached["pointers"];
  45091. if (pointers) {
  45092. pointers.angularSensibilityY = value;
  45093. }
  45094. },
  45095. enumerable: true,
  45096. configurable: true
  45097. });
  45098. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45099. get: function () {
  45100. var pointers = this.inputs.attached["pointers"];
  45101. if (pointers)
  45102. return pointers.pinchPrecision;
  45103. return 0;
  45104. },
  45105. set: function (value) {
  45106. var pointers = this.inputs.attached["pointers"];
  45107. if (pointers) {
  45108. pointers.pinchPrecision = value;
  45109. }
  45110. },
  45111. enumerable: true,
  45112. configurable: true
  45113. });
  45114. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45115. get: function () {
  45116. var pointers = this.inputs.attached["pointers"];
  45117. if (pointers)
  45118. return pointers.pinchDeltaPercentage;
  45119. return 0;
  45120. },
  45121. set: function (value) {
  45122. var pointers = this.inputs.attached["pointers"];
  45123. if (pointers) {
  45124. pointers.pinchDeltaPercentage = value;
  45125. }
  45126. },
  45127. enumerable: true,
  45128. configurable: true
  45129. });
  45130. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45131. get: function () {
  45132. var pointers = this.inputs.attached["pointers"];
  45133. if (pointers)
  45134. return pointers.panningSensibility;
  45135. return 0;
  45136. },
  45137. set: function (value) {
  45138. var pointers = this.inputs.attached["pointers"];
  45139. if (pointers) {
  45140. pointers.panningSensibility = value;
  45141. }
  45142. },
  45143. enumerable: true,
  45144. configurable: true
  45145. });
  45146. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45147. get: function () {
  45148. var keyboard = this.inputs.attached["keyboard"];
  45149. if (keyboard)
  45150. return keyboard.keysUp;
  45151. return [];
  45152. },
  45153. set: function (value) {
  45154. var keyboard = this.inputs.attached["keyboard"];
  45155. if (keyboard)
  45156. keyboard.keysUp = value;
  45157. },
  45158. enumerable: true,
  45159. configurable: true
  45160. });
  45161. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45162. get: function () {
  45163. var keyboard = this.inputs.attached["keyboard"];
  45164. if (keyboard)
  45165. return keyboard.keysDown;
  45166. return [];
  45167. },
  45168. set: function (value) {
  45169. var keyboard = this.inputs.attached["keyboard"];
  45170. if (keyboard)
  45171. keyboard.keysDown = value;
  45172. },
  45173. enumerable: true,
  45174. configurable: true
  45175. });
  45176. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45177. get: function () {
  45178. var keyboard = this.inputs.attached["keyboard"];
  45179. if (keyboard)
  45180. return keyboard.keysLeft;
  45181. return [];
  45182. },
  45183. set: function (value) {
  45184. var keyboard = this.inputs.attached["keyboard"];
  45185. if (keyboard)
  45186. keyboard.keysLeft = value;
  45187. },
  45188. enumerable: true,
  45189. configurable: true
  45190. });
  45191. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45192. get: function () {
  45193. var keyboard = this.inputs.attached["keyboard"];
  45194. if (keyboard)
  45195. return keyboard.keysRight;
  45196. return [];
  45197. },
  45198. set: function (value) {
  45199. var keyboard = this.inputs.attached["keyboard"];
  45200. if (keyboard)
  45201. keyboard.keysRight = value;
  45202. },
  45203. enumerable: true,
  45204. configurable: true
  45205. });
  45206. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45207. get: function () {
  45208. var mousewheel = this.inputs.attached["mousewheel"];
  45209. if (mousewheel)
  45210. return mousewheel.wheelPrecision;
  45211. return 0;
  45212. },
  45213. set: function (value) {
  45214. var mousewheel = this.inputs.attached["mousewheel"];
  45215. if (mousewheel)
  45216. mousewheel.wheelPrecision = value;
  45217. },
  45218. enumerable: true,
  45219. configurable: true
  45220. });
  45221. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45222. get: function () {
  45223. var mousewheel = this.inputs.attached["mousewheel"];
  45224. if (mousewheel)
  45225. return mousewheel.wheelDeltaPercentage;
  45226. return 0;
  45227. },
  45228. set: function (value) {
  45229. var mousewheel = this.inputs.attached["mousewheel"];
  45230. if (mousewheel)
  45231. mousewheel.wheelDeltaPercentage = value;
  45232. },
  45233. enumerable: true,
  45234. configurable: true
  45235. });
  45236. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45237. get: function () {
  45238. return this._bouncingBehavior;
  45239. },
  45240. enumerable: true,
  45241. configurable: true
  45242. });
  45243. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45244. get: function () {
  45245. return this._bouncingBehavior != null;
  45246. },
  45247. set: function (value) {
  45248. if (value === this.useBouncingBehavior) {
  45249. return;
  45250. }
  45251. if (value) {
  45252. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45253. this.addBehavior(this._bouncingBehavior);
  45254. }
  45255. else if (this._bouncingBehavior) {
  45256. this.removeBehavior(this._bouncingBehavior);
  45257. this._bouncingBehavior = null;
  45258. }
  45259. },
  45260. enumerable: true,
  45261. configurable: true
  45262. });
  45263. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45264. get: function () {
  45265. return this._framingBehavior;
  45266. },
  45267. enumerable: true,
  45268. configurable: true
  45269. });
  45270. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45271. get: function () {
  45272. return this._framingBehavior != null;
  45273. },
  45274. set: function (value) {
  45275. if (value === this.useFramingBehavior) {
  45276. return;
  45277. }
  45278. if (value) {
  45279. this._framingBehavior = new BABYLON.FramingBehavior();
  45280. this.addBehavior(this._framingBehavior);
  45281. }
  45282. else if (this._framingBehavior) {
  45283. this.removeBehavior(this._framingBehavior);
  45284. this._framingBehavior = null;
  45285. }
  45286. },
  45287. enumerable: true,
  45288. configurable: true
  45289. });
  45290. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45291. get: function () {
  45292. return this._autoRotationBehavior;
  45293. },
  45294. enumerable: true,
  45295. configurable: true
  45296. });
  45297. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45298. get: function () {
  45299. return this._autoRotationBehavior != null;
  45300. },
  45301. set: function (value) {
  45302. if (value === this.useAutoRotationBehavior) {
  45303. return;
  45304. }
  45305. if (value) {
  45306. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45307. this.addBehavior(this._autoRotationBehavior);
  45308. }
  45309. else if (this._autoRotationBehavior) {
  45310. this.removeBehavior(this._autoRotationBehavior);
  45311. this._autoRotationBehavior = null;
  45312. }
  45313. },
  45314. enumerable: true,
  45315. configurable: true
  45316. });
  45317. // Cache
  45318. ArcRotateCamera.prototype._initCache = function () {
  45319. _super.prototype._initCache.call(this);
  45320. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45321. this._cache.alpha = undefined;
  45322. this._cache.beta = undefined;
  45323. this._cache.radius = undefined;
  45324. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45325. };
  45326. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45327. if (!ignoreParentClass) {
  45328. _super.prototype._updateCache.call(this);
  45329. }
  45330. this._cache._target.copyFrom(this._getTargetPosition());
  45331. this._cache.alpha = this.alpha;
  45332. this._cache.beta = this.beta;
  45333. this._cache.radius = this.radius;
  45334. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45335. };
  45336. ArcRotateCamera.prototype._getTargetPosition = function () {
  45337. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45338. var pos = this._targetHost.getAbsolutePosition();
  45339. if (this._targetBoundingCenter) {
  45340. pos.addToRef(this._targetBoundingCenter, this._target);
  45341. }
  45342. else {
  45343. this._target.copyFrom(pos);
  45344. }
  45345. }
  45346. var lockedTargetPosition = this._getLockedTargetPosition();
  45347. if (lockedTargetPosition) {
  45348. return lockedTargetPosition;
  45349. }
  45350. return this._target;
  45351. };
  45352. ArcRotateCamera.prototype.storeState = function () {
  45353. this._storedAlpha = this.alpha;
  45354. this._storedBeta = this.beta;
  45355. this._storedRadius = this.radius;
  45356. this._storedTarget = this._getTargetPosition().clone();
  45357. return _super.prototype.storeState.call(this);
  45358. };
  45359. /**
  45360. * Restored camera state. You must call storeState() first
  45361. */
  45362. ArcRotateCamera.prototype._restoreStateValues = function () {
  45363. if (!_super.prototype._restoreStateValues.call(this)) {
  45364. return false;
  45365. }
  45366. this.alpha = this._storedAlpha;
  45367. this.beta = this._storedBeta;
  45368. this.radius = this._storedRadius;
  45369. this.setTarget(this._storedTarget.clone());
  45370. this.inertialAlphaOffset = 0;
  45371. this.inertialBetaOffset = 0;
  45372. this.inertialRadiusOffset = 0;
  45373. this.inertialPanningX = 0;
  45374. this.inertialPanningY = 0;
  45375. return true;
  45376. };
  45377. // Synchronized
  45378. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45379. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45380. return false;
  45381. return this._cache._target.equals(this._getTargetPosition())
  45382. && this._cache.alpha === this.alpha
  45383. && this._cache.beta === this.beta
  45384. && this._cache.radius === this.radius
  45385. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45386. };
  45387. // Methods
  45388. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45389. var _this = this;
  45390. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45391. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45392. this._useCtrlForPanning = useCtrlForPanning;
  45393. this._panningMouseButton = panningMouseButton;
  45394. this.inputs.attachElement(element, noPreventDefault);
  45395. this._reset = function () {
  45396. _this.inertialAlphaOffset = 0;
  45397. _this.inertialBetaOffset = 0;
  45398. _this.inertialRadiusOffset = 0;
  45399. _this.inertialPanningX = 0;
  45400. _this.inertialPanningY = 0;
  45401. };
  45402. };
  45403. ArcRotateCamera.prototype.detachControl = function (element) {
  45404. this.inputs.detachElement(element);
  45405. if (this._reset) {
  45406. this._reset();
  45407. }
  45408. };
  45409. ArcRotateCamera.prototype._checkInputs = function () {
  45410. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45411. if (this._collisionTriggered) {
  45412. return;
  45413. }
  45414. this.inputs.checkInputs();
  45415. // Inertia
  45416. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45417. if (this.getScene().useRightHandedSystem) {
  45418. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45419. }
  45420. else {
  45421. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45422. }
  45423. this.beta += this.inertialBetaOffset;
  45424. this.radius -= this.inertialRadiusOffset;
  45425. this.inertialAlphaOffset *= this.inertia;
  45426. this.inertialBetaOffset *= this.inertia;
  45427. this.inertialRadiusOffset *= this.inertia;
  45428. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45429. this.inertialAlphaOffset = 0;
  45430. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45431. this.inertialBetaOffset = 0;
  45432. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45433. this.inertialRadiusOffset = 0;
  45434. }
  45435. // Panning inertia
  45436. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45437. if (!this._localDirection) {
  45438. this._localDirection = BABYLON.Vector3.Zero();
  45439. this._transformedDirection = BABYLON.Vector3.Zero();
  45440. }
  45441. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45442. this._localDirection.multiplyInPlace(this.panningAxis);
  45443. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45444. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45445. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45446. if (!this.panningAxis.y) {
  45447. this._transformedDirection.y = 0;
  45448. }
  45449. if (!this._targetHost) {
  45450. if (this.panningDistanceLimit) {
  45451. this._transformedDirection.addInPlace(this._target);
  45452. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45453. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45454. this._target.copyFrom(this._transformedDirection);
  45455. }
  45456. }
  45457. else {
  45458. this._target.addInPlace(this._transformedDirection);
  45459. }
  45460. }
  45461. this.inertialPanningX *= this.panningInertia;
  45462. this.inertialPanningY *= this.panningInertia;
  45463. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45464. this.inertialPanningX = 0;
  45465. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45466. this.inertialPanningY = 0;
  45467. }
  45468. // Limits
  45469. this._checkLimits();
  45470. _super.prototype._checkInputs.call(this);
  45471. };
  45472. ArcRotateCamera.prototype._checkLimits = function () {
  45473. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45474. if (this.allowUpsideDown && this.beta > Math.PI) {
  45475. this.beta = this.beta - (2 * Math.PI);
  45476. }
  45477. }
  45478. else {
  45479. if (this.beta < this.lowerBetaLimit) {
  45480. this.beta = this.lowerBetaLimit;
  45481. }
  45482. }
  45483. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45484. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45485. this.beta = this.beta + (2 * Math.PI);
  45486. }
  45487. }
  45488. else {
  45489. if (this.beta > this.upperBetaLimit) {
  45490. this.beta = this.upperBetaLimit;
  45491. }
  45492. }
  45493. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45494. this.alpha = this.lowerAlphaLimit;
  45495. }
  45496. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45497. this.alpha = this.upperAlphaLimit;
  45498. }
  45499. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45500. this.radius = this.lowerRadiusLimit;
  45501. }
  45502. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45503. this.radius = this.upperRadiusLimit;
  45504. }
  45505. };
  45506. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45507. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45508. this.radius = this._computationVector.length();
  45509. if (this.radius === 0) {
  45510. this.radius = 0.0001; // Just to avoid division by zero
  45511. }
  45512. // Alpha
  45513. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45514. if (this._computationVector.z < 0) {
  45515. this.alpha = 2 * Math.PI - this.alpha;
  45516. }
  45517. // Beta
  45518. this.beta = Math.acos(this._computationVector.y / this.radius);
  45519. this._checkLimits();
  45520. };
  45521. ArcRotateCamera.prototype.setPosition = function (position) {
  45522. if (this.position.equals(position)) {
  45523. return;
  45524. }
  45525. this.position.copyFrom(position);
  45526. this.rebuildAnglesAndRadius();
  45527. };
  45528. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45529. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45530. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45531. if (target.getBoundingInfo) {
  45532. if (toBoundingCenter) {
  45533. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45534. }
  45535. else {
  45536. this._targetBoundingCenter = null;
  45537. }
  45538. this._targetHost = target;
  45539. this._target = this._getTargetPosition();
  45540. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45541. }
  45542. else {
  45543. var newTarget = target;
  45544. var currentTarget = this._getTargetPosition();
  45545. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45546. return;
  45547. }
  45548. this._targetHost = null;
  45549. this._target = newTarget;
  45550. this._targetBoundingCenter = null;
  45551. this.onMeshTargetChangedObservable.notifyObservers(null);
  45552. }
  45553. this.rebuildAnglesAndRadius();
  45554. };
  45555. ArcRotateCamera.prototype._getViewMatrix = function () {
  45556. // Compute
  45557. var cosa = Math.cos(this.alpha);
  45558. var sina = Math.sin(this.alpha);
  45559. var cosb = Math.cos(this.beta);
  45560. var sinb = Math.sin(this.beta);
  45561. if (sinb === 0) {
  45562. sinb = 0.0001;
  45563. }
  45564. var target = this._getTargetPosition();
  45565. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45566. target.addToRef(this._computationVector, this._newPosition);
  45567. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45568. if (!this._collider) {
  45569. this._collider = new BABYLON.Collider();
  45570. }
  45571. this._collider._radius = this.collisionRadius;
  45572. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45573. this._collisionTriggered = true;
  45574. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45575. }
  45576. else {
  45577. this.position.copyFrom(this._newPosition);
  45578. var up = this.upVector;
  45579. if (this.allowUpsideDown && sinb < 0) {
  45580. up = up.clone();
  45581. up = up.negate();
  45582. }
  45583. if (this.getScene().useRightHandedSystem) {
  45584. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45585. }
  45586. else {
  45587. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45588. }
  45589. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45590. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45591. }
  45592. this._currentTarget = target;
  45593. return this._viewMatrix;
  45594. };
  45595. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45596. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45597. meshes = meshes || this.getScene().meshes;
  45598. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45599. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45600. this.radius = distance * this.zoomOnFactor;
  45601. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45602. };
  45603. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45604. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45605. var meshesOrMinMaxVector;
  45606. var distance;
  45607. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45608. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45609. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45610. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45611. }
  45612. else {
  45613. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45614. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45615. distance = minMaxVectorAndDistance.distance;
  45616. }
  45617. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45618. if (!doNotUpdateMaxZ) {
  45619. this.maxZ = distance * 2;
  45620. }
  45621. };
  45622. /**
  45623. * @override
  45624. * Override Camera.createRigCamera
  45625. */
  45626. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45627. var alphaShift = 0;
  45628. switch (this.cameraRigMode) {
  45629. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45630. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45631. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45632. case BABYLON.Camera.RIG_MODE_VR:
  45633. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45634. break;
  45635. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45636. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45637. break;
  45638. }
  45639. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45640. rigCam._cameraRigParams = {};
  45641. return rigCam;
  45642. };
  45643. /**
  45644. * @override
  45645. * Override Camera._updateRigCameras
  45646. */
  45647. ArcRotateCamera.prototype._updateRigCameras = function () {
  45648. var camLeft = this._rigCameras[0];
  45649. var camRight = this._rigCameras[1];
  45650. camLeft.beta = camRight.beta = this.beta;
  45651. camLeft.radius = camRight.radius = this.radius;
  45652. switch (this.cameraRigMode) {
  45653. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45654. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45655. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45656. case BABYLON.Camera.RIG_MODE_VR:
  45657. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45658. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45659. break;
  45660. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45661. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45662. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45663. break;
  45664. }
  45665. _super.prototype._updateRigCameras.call(this);
  45666. };
  45667. ArcRotateCamera.prototype.dispose = function () {
  45668. this.inputs.clear();
  45669. _super.prototype.dispose.call(this);
  45670. };
  45671. ArcRotateCamera.prototype.getClassName = function () {
  45672. return "ArcRotateCamera";
  45673. };
  45674. __decorate([
  45675. BABYLON.serialize()
  45676. ], ArcRotateCamera.prototype, "alpha", void 0);
  45677. __decorate([
  45678. BABYLON.serialize()
  45679. ], ArcRotateCamera.prototype, "beta", void 0);
  45680. __decorate([
  45681. BABYLON.serialize()
  45682. ], ArcRotateCamera.prototype, "radius", void 0);
  45683. __decorate([
  45684. BABYLON.serializeAsVector3("target")
  45685. ], ArcRotateCamera.prototype, "_target", void 0);
  45686. __decorate([
  45687. BABYLON.serialize()
  45688. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45689. __decorate([
  45690. BABYLON.serialize()
  45691. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45692. __decorate([
  45693. BABYLON.serialize()
  45694. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45695. __decorate([
  45696. BABYLON.serialize()
  45697. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45698. __decorate([
  45699. BABYLON.serialize()
  45700. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45701. __decorate([
  45702. BABYLON.serialize()
  45703. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45704. __decorate([
  45705. BABYLON.serialize()
  45706. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45707. __decorate([
  45708. BABYLON.serialize()
  45709. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45710. __decorate([
  45711. BABYLON.serialize()
  45712. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45713. __decorate([
  45714. BABYLON.serialize()
  45715. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45716. __decorate([
  45717. BABYLON.serialize()
  45718. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45719. __decorate([
  45720. BABYLON.serialize()
  45721. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45722. __decorate([
  45723. BABYLON.serialize()
  45724. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45725. __decorate([
  45726. BABYLON.serializeAsVector3()
  45727. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45728. __decorate([
  45729. BABYLON.serialize()
  45730. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45731. __decorate([
  45732. BABYLON.serialize()
  45733. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45734. __decorate([
  45735. BABYLON.serialize()
  45736. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45737. return ArcRotateCamera;
  45738. }(BABYLON.TargetCamera));
  45739. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45740. })(BABYLON || (BABYLON = {}));
  45741. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45742. "use strict";
  45743. var BABYLON;
  45744. (function (BABYLON) {
  45745. /**
  45746. * The HemisphericLight simulates the ambient environment light,
  45747. * so the passed direction is the light reflection direction, not the incoming direction.
  45748. */
  45749. var HemisphericLight = /** @class */ (function (_super) {
  45750. __extends(HemisphericLight, _super);
  45751. /**
  45752. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45753. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45754. * The HemisphericLight can't cast shadows.
  45755. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45756. * @param name The friendly name of the light
  45757. * @param direction The direction of the light reflection
  45758. * @param scene The scene the light belongs to
  45759. */
  45760. function HemisphericLight(name, direction, scene) {
  45761. var _this = _super.call(this, name, scene) || this;
  45762. /**
  45763. * The groundColor is the light in the opposite direction to the one specified during creation.
  45764. * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
  45765. */
  45766. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45767. _this.direction = direction || BABYLON.Vector3.Up();
  45768. return _this;
  45769. }
  45770. HemisphericLight.prototype._buildUniformLayout = function () {
  45771. this._uniformBuffer.addUniform("vLightData", 4);
  45772. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45773. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45774. this._uniformBuffer.addUniform("vLightGround", 3);
  45775. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45776. this._uniformBuffer.addUniform("depthValues", 2);
  45777. this._uniformBuffer.create();
  45778. };
  45779. /**
  45780. * Returns the string "HemisphericLight".
  45781. * @return The class name
  45782. */
  45783. HemisphericLight.prototype.getClassName = function () {
  45784. return "HemisphericLight";
  45785. };
  45786. /**
  45787. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45788. * Returns the updated direction.
  45789. * @param target The target the direction should point to
  45790. * @return The computed direction
  45791. */
  45792. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45793. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45794. return this.direction;
  45795. };
  45796. /**
  45797. * Returns the shadow generator associated to the light.
  45798. * @returns Always null for hemispheric lights because it does not support shadows.
  45799. */
  45800. HemisphericLight.prototype.getShadowGenerator = function () {
  45801. return null;
  45802. };
  45803. /**
  45804. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45805. * @param effect The effect to update
  45806. * @param lightIndex The index of the light in the effect to update
  45807. * @returns The hemispheric light
  45808. */
  45809. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45810. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45811. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45812. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45813. return this;
  45814. };
  45815. /**
  45816. * @ignore internal use only.
  45817. */
  45818. HemisphericLight.prototype._getWorldMatrix = function () {
  45819. if (!this._worldMatrix) {
  45820. this._worldMatrix = BABYLON.Matrix.Identity();
  45821. }
  45822. return this._worldMatrix;
  45823. };
  45824. /**
  45825. * Returns the integer 3.
  45826. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45827. */
  45828. HemisphericLight.prototype.getTypeID = function () {
  45829. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45830. };
  45831. __decorate([
  45832. BABYLON.serializeAsColor3()
  45833. ], HemisphericLight.prototype, "groundColor", void 0);
  45834. __decorate([
  45835. BABYLON.serializeAsVector3()
  45836. ], HemisphericLight.prototype, "direction", void 0);
  45837. return HemisphericLight;
  45838. }(BABYLON.Light));
  45839. BABYLON.HemisphericLight = HemisphericLight;
  45840. })(BABYLON || (BABYLON = {}));
  45841. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45842. "use strict";
  45843. var BABYLON;
  45844. (function (BABYLON) {
  45845. /**
  45846. * Base implementation of @see IShadowLight
  45847. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45848. */
  45849. var ShadowLight = /** @class */ (function (_super) {
  45850. __extends(ShadowLight, _super);
  45851. function ShadowLight() {
  45852. var _this = _super !== null && _super.apply(this, arguments) || this;
  45853. _this._needProjectionMatrixCompute = true;
  45854. return _this;
  45855. }
  45856. ShadowLight.prototype._setPosition = function (value) {
  45857. this._position = value;
  45858. };
  45859. Object.defineProperty(ShadowLight.prototype, "position", {
  45860. /**
  45861. * Sets the position the shadow will be casted from. Also use as the light position for both
  45862. * point and spot lights.
  45863. */
  45864. get: function () {
  45865. return this._position;
  45866. },
  45867. /**
  45868. * Sets the position the shadow will be casted from. Also use as the light position for both
  45869. * point and spot lights.
  45870. */
  45871. set: function (value) {
  45872. this._setPosition(value);
  45873. },
  45874. enumerable: true,
  45875. configurable: true
  45876. });
  45877. ShadowLight.prototype._setDirection = function (value) {
  45878. this._direction = value;
  45879. };
  45880. Object.defineProperty(ShadowLight.prototype, "direction", {
  45881. /**
  45882. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45883. * Also use as the light direction on spot and directional lights.
  45884. */
  45885. get: function () {
  45886. return this._direction;
  45887. },
  45888. /**
  45889. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45890. * Also use as the light direction on spot and directional lights.
  45891. */
  45892. set: function (value) {
  45893. this._setDirection(value);
  45894. },
  45895. enumerable: true,
  45896. configurable: true
  45897. });
  45898. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45899. /**
  45900. * Gets the shadow projection clipping minimum z value.
  45901. */
  45902. get: function () {
  45903. return this._shadowMinZ;
  45904. },
  45905. /**
  45906. * Sets the shadow projection clipping minimum z value.
  45907. */
  45908. set: function (value) {
  45909. this._shadowMinZ = value;
  45910. this.forceProjectionMatrixCompute();
  45911. },
  45912. enumerable: true,
  45913. configurable: true
  45914. });
  45915. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45916. /**
  45917. * Sets the shadow projection clipping maximum z value.
  45918. */
  45919. get: function () {
  45920. return this._shadowMaxZ;
  45921. },
  45922. /**
  45923. * Gets the shadow projection clipping maximum z value.
  45924. */
  45925. set: function (value) {
  45926. this._shadowMaxZ = value;
  45927. this.forceProjectionMatrixCompute();
  45928. },
  45929. enumerable: true,
  45930. configurable: true
  45931. });
  45932. /**
  45933. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45934. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45935. */
  45936. ShadowLight.prototype.computeTransformedInformation = function () {
  45937. if (this.parent && this.parent.getWorldMatrix) {
  45938. if (!this.transformedPosition) {
  45939. this.transformedPosition = BABYLON.Vector3.Zero();
  45940. }
  45941. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45942. // In case the direction is present.
  45943. if (this.direction) {
  45944. if (!this.transformedDirection) {
  45945. this.transformedDirection = BABYLON.Vector3.Zero();
  45946. }
  45947. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45948. }
  45949. return true;
  45950. }
  45951. return false;
  45952. };
  45953. /**
  45954. * Return the depth scale used for the shadow map.
  45955. * @returns the depth scale.
  45956. */
  45957. ShadowLight.prototype.getDepthScale = function () {
  45958. return 50.0;
  45959. };
  45960. /**
  45961. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45962. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45963. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45964. */
  45965. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45966. return this.transformedDirection ? this.transformedDirection : this.direction;
  45967. };
  45968. /**
  45969. * Returns the ShadowLight absolute position in the World.
  45970. * @returns the position vector in world space
  45971. */
  45972. ShadowLight.prototype.getAbsolutePosition = function () {
  45973. return this.transformedPosition ? this.transformedPosition : this.position;
  45974. };
  45975. /**
  45976. * Sets the ShadowLight direction toward the passed target.
  45977. * @param target The point tot target in local space
  45978. * @returns the updated ShadowLight direction
  45979. */
  45980. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45981. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45982. return this.direction;
  45983. };
  45984. /**
  45985. * Returns the light rotation in euler definition.
  45986. * @returns the x y z rotation in local space.
  45987. */
  45988. ShadowLight.prototype.getRotation = function () {
  45989. this.direction.normalize();
  45990. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45991. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45992. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45993. };
  45994. /**
  45995. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45996. * @returns true if a cube texture needs to be use
  45997. */
  45998. ShadowLight.prototype.needCube = function () {
  45999. return false;
  46000. };
  46001. /**
  46002. * Detects if the projection matrix requires to be recomputed this frame.
  46003. * @returns true if it requires to be recomputed otherwise, false.
  46004. */
  46005. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46006. return this._needProjectionMatrixCompute;
  46007. };
  46008. /**
  46009. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46010. */
  46011. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46012. this._needProjectionMatrixCompute = true;
  46013. };
  46014. /**
  46015. * Get the world matrix of the sahdow lights.
  46016. * @ignore Internal Use Only
  46017. */
  46018. ShadowLight.prototype._getWorldMatrix = function () {
  46019. if (!this._worldMatrix) {
  46020. this._worldMatrix = BABYLON.Matrix.Identity();
  46021. }
  46022. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46023. return this._worldMatrix;
  46024. };
  46025. /**
  46026. * Gets the minZ used for shadow according to both the scene and the light.
  46027. * @param activeCamera The camera we are returning the min for
  46028. * @returns the depth min z
  46029. */
  46030. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46031. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46032. };
  46033. /**
  46034. * Gets the maxZ used for shadow according to both the scene and the light.
  46035. * @param activeCamera The camera we are returning the max for
  46036. * @returns the depth max z
  46037. */
  46038. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46039. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46040. };
  46041. /**
  46042. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46043. * @param matrix The materix to updated with the projection information
  46044. * @param viewMatrix The transform matrix of the light
  46045. * @param renderList The list of mesh to render in the map
  46046. * @returns The current light
  46047. */
  46048. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46049. if (this.customProjectionMatrixBuilder) {
  46050. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46051. }
  46052. else {
  46053. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46054. }
  46055. return this;
  46056. };
  46057. __decorate([
  46058. BABYLON.serializeAsVector3()
  46059. ], ShadowLight.prototype, "position", null);
  46060. __decorate([
  46061. BABYLON.serializeAsVector3()
  46062. ], ShadowLight.prototype, "direction", null);
  46063. __decorate([
  46064. BABYLON.serialize()
  46065. ], ShadowLight.prototype, "shadowMinZ", null);
  46066. __decorate([
  46067. BABYLON.serialize()
  46068. ], ShadowLight.prototype, "shadowMaxZ", null);
  46069. return ShadowLight;
  46070. }(BABYLON.Light));
  46071. BABYLON.ShadowLight = ShadowLight;
  46072. })(BABYLON || (BABYLON = {}));
  46073. //# sourceMappingURL=babylon.shadowLight.js.map
  46074. "use strict";
  46075. var BABYLON;
  46076. (function (BABYLON) {
  46077. /**
  46078. * A point light is a light defined by an unique point in world space.
  46079. * The light is emitted in every direction from this point.
  46080. * A good example of a point light is a standard light bulb.
  46081. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46082. */
  46083. var PointLight = /** @class */ (function (_super) {
  46084. __extends(PointLight, _super);
  46085. /**
  46086. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46087. * A PointLight emits the light in every direction.
  46088. * It can cast shadows.
  46089. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46090. * ```javascript
  46091. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46092. * ```
  46093. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46094. * @param name The light friendly name
  46095. * @param position The position of the point light in the scene
  46096. * @param scene The scene the lights belongs to
  46097. */
  46098. function PointLight(name, position, scene) {
  46099. var _this = _super.call(this, name, scene) || this;
  46100. _this._shadowAngle = Math.PI / 2;
  46101. _this.position = position;
  46102. return _this;
  46103. }
  46104. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46105. /**
  46106. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46107. * This specifies what angle the shadow will use to be created.
  46108. *
  46109. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46110. */
  46111. get: function () {
  46112. return this._shadowAngle;
  46113. },
  46114. /**
  46115. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46116. * This specifies what angle the shadow will use to be created.
  46117. *
  46118. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46119. */
  46120. set: function (value) {
  46121. this._shadowAngle = value;
  46122. this.forceProjectionMatrixCompute();
  46123. },
  46124. enumerable: true,
  46125. configurable: true
  46126. });
  46127. Object.defineProperty(PointLight.prototype, "direction", {
  46128. /**
  46129. * Gets the direction if it has been set.
  46130. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46131. */
  46132. get: function () {
  46133. return this._direction;
  46134. },
  46135. /**
  46136. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46137. */
  46138. set: function (value) {
  46139. var previousNeedCube = this.needCube();
  46140. this._direction = value;
  46141. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46142. this._shadowGenerator.recreateShadowMap();
  46143. }
  46144. },
  46145. enumerable: true,
  46146. configurable: true
  46147. });
  46148. /**
  46149. * Returns the string "PointLight"
  46150. * @returns the class name
  46151. */
  46152. PointLight.prototype.getClassName = function () {
  46153. return "PointLight";
  46154. };
  46155. /**
  46156. * Returns the integer 0.
  46157. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46158. */
  46159. PointLight.prototype.getTypeID = function () {
  46160. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46161. };
  46162. /**
  46163. * Specifies wether or not the shadowmap should be a cube texture.
  46164. * @returns true if the shadowmap needs to be a cube texture.
  46165. */
  46166. PointLight.prototype.needCube = function () {
  46167. return !this.direction;
  46168. };
  46169. /**
  46170. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46171. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46172. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46173. */
  46174. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46175. if (this.direction) {
  46176. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46177. }
  46178. else {
  46179. switch (faceIndex) {
  46180. case 0:
  46181. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46182. case 1:
  46183. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46184. case 2:
  46185. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46186. case 3:
  46187. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46188. case 4:
  46189. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46190. case 5:
  46191. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46192. }
  46193. }
  46194. return BABYLON.Vector3.Zero();
  46195. };
  46196. /**
  46197. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46198. * - fov = PI / 2
  46199. * - aspect ratio : 1.0
  46200. * - z-near and far equal to the active camera minZ and maxZ.
  46201. * Returns the PointLight.
  46202. */
  46203. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46204. var activeCamera = this.getScene().activeCamera;
  46205. if (!activeCamera) {
  46206. return;
  46207. }
  46208. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46209. };
  46210. PointLight.prototype._buildUniformLayout = function () {
  46211. this._uniformBuffer.addUniform("vLightData", 4);
  46212. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46213. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46214. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46215. this._uniformBuffer.addUniform("depthValues", 2);
  46216. this._uniformBuffer.create();
  46217. };
  46218. /**
  46219. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46220. * @param effect The effect to update
  46221. * @param lightIndex The index of the light in the effect to update
  46222. * @returns The point light
  46223. */
  46224. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46225. if (this.computeTransformedInformation()) {
  46226. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46227. return this;
  46228. }
  46229. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46230. return this;
  46231. };
  46232. __decorate([
  46233. BABYLON.serialize()
  46234. ], PointLight.prototype, "shadowAngle", null);
  46235. return PointLight;
  46236. }(BABYLON.ShadowLight));
  46237. BABYLON.PointLight = PointLight;
  46238. })(BABYLON || (BABYLON = {}));
  46239. //# sourceMappingURL=babylon.pointLight.js.map
  46240. "use strict";
  46241. var BABYLON;
  46242. (function (BABYLON) {
  46243. /**
  46244. * A directional light is defined by a direction (what a surprise!).
  46245. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46246. * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
  46247. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46248. */
  46249. var DirectionalLight = /** @class */ (function (_super) {
  46250. __extends(DirectionalLight, _super);
  46251. /**
  46252. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46253. * The directional light is emitted from everywhere in the given direction.
  46254. * It can cast shawdows.
  46255. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46256. * @param name The friendly name of the light
  46257. * @param direction The direction of the light
  46258. * @param scene The scene the light belongs to
  46259. */
  46260. function DirectionalLight(name, direction, scene) {
  46261. var _this = _super.call(this, name, scene) || this;
  46262. _this._shadowFrustumSize = 0;
  46263. _this._shadowOrthoScale = 0.1;
  46264. /**
  46265. * Automatically compute the projection matrix to best fit (including all the casters)
  46266. * on each frame.
  46267. */
  46268. _this.autoUpdateExtends = true;
  46269. // Cache
  46270. _this._orthoLeft = Number.MAX_VALUE;
  46271. _this._orthoRight = Number.MIN_VALUE;
  46272. _this._orthoTop = Number.MIN_VALUE;
  46273. _this._orthoBottom = Number.MAX_VALUE;
  46274. _this.position = direction.scale(-1.0);
  46275. _this.direction = direction;
  46276. return _this;
  46277. }
  46278. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46279. /**
  46280. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46281. */
  46282. get: function () {
  46283. return this._shadowFrustumSize;
  46284. },
  46285. /**
  46286. * Specifies a fix frustum size for the shadow generation.
  46287. */
  46288. set: function (value) {
  46289. this._shadowFrustumSize = value;
  46290. this.forceProjectionMatrixCompute();
  46291. },
  46292. enumerable: true,
  46293. configurable: true
  46294. });
  46295. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46296. /**
  46297. * Gets the shadow projection scale against the optimal computed one.
  46298. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46299. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46300. */
  46301. get: function () {
  46302. return this._shadowOrthoScale;
  46303. },
  46304. /**
  46305. * Sets the shadow projection scale against the optimal computed one.
  46306. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46307. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46308. */
  46309. set: function (value) {
  46310. this._shadowOrthoScale = value;
  46311. this.forceProjectionMatrixCompute();
  46312. },
  46313. enumerable: true,
  46314. configurable: true
  46315. });
  46316. /**
  46317. * Returns the string "DirectionalLight".
  46318. * @return The class name
  46319. */
  46320. DirectionalLight.prototype.getClassName = function () {
  46321. return "DirectionalLight";
  46322. };
  46323. /**
  46324. * Returns the integer 1.
  46325. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46326. */
  46327. DirectionalLight.prototype.getTypeID = function () {
  46328. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46329. };
  46330. /**
  46331. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46332. * Returns the DirectionalLight Shadow projection matrix.
  46333. */
  46334. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46335. if (this.shadowFrustumSize > 0) {
  46336. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46337. }
  46338. else {
  46339. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46340. }
  46341. };
  46342. /**
  46343. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46344. * Returns the DirectionalLight Shadow projection matrix.
  46345. */
  46346. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46347. var activeCamera = this.getScene().activeCamera;
  46348. if (!activeCamera) {
  46349. return;
  46350. }
  46351. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46352. };
  46353. /**
  46354. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46355. * Returns the DirectionalLight Shadow projection matrix.
  46356. */
  46357. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46358. var activeCamera = this.getScene().activeCamera;
  46359. if (!activeCamera) {
  46360. return;
  46361. }
  46362. // Check extends
  46363. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46364. var tempVector3 = BABYLON.Vector3.Zero();
  46365. this._orthoLeft = Number.MAX_VALUE;
  46366. this._orthoRight = Number.MIN_VALUE;
  46367. this._orthoTop = Number.MIN_VALUE;
  46368. this._orthoBottom = Number.MAX_VALUE;
  46369. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46370. var mesh = renderList[meshIndex];
  46371. if (!mesh) {
  46372. continue;
  46373. }
  46374. var boundingInfo = mesh.getBoundingInfo();
  46375. var boundingBox = boundingInfo.boundingBox;
  46376. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46377. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46378. if (tempVector3.x < this._orthoLeft)
  46379. this._orthoLeft = tempVector3.x;
  46380. if (tempVector3.y < this._orthoBottom)
  46381. this._orthoBottom = tempVector3.y;
  46382. if (tempVector3.x > this._orthoRight)
  46383. this._orthoRight = tempVector3.x;
  46384. if (tempVector3.y > this._orthoTop)
  46385. this._orthoTop = tempVector3.y;
  46386. }
  46387. }
  46388. }
  46389. var xOffset = this._orthoRight - this._orthoLeft;
  46390. var yOffset = this._orthoTop - this._orthoBottom;
  46391. 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);
  46392. };
  46393. DirectionalLight.prototype._buildUniformLayout = function () {
  46394. this._uniformBuffer.addUniform("vLightData", 4);
  46395. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46396. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46397. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46398. this._uniformBuffer.addUniform("depthValues", 2);
  46399. this._uniformBuffer.create();
  46400. };
  46401. /**
  46402. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46403. * @param effect The effect to update
  46404. * @param lightIndex The index of the light in the effect to update
  46405. * @returns The directional light
  46406. */
  46407. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46408. if (this.computeTransformedInformation()) {
  46409. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46410. return this;
  46411. }
  46412. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46413. return this;
  46414. };
  46415. /**
  46416. * Gets the minZ used for shadow according to both the scene and the light.
  46417. *
  46418. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46419. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46420. * @param activeCamera The camera we are returning the min for
  46421. * @returns the depth min z
  46422. */
  46423. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46424. return 1;
  46425. };
  46426. /**
  46427. * Gets the maxZ used for shadow according to both the scene and the light.
  46428. *
  46429. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46430. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46431. * @param activeCamera The camera we are returning the max for
  46432. * @returns the depth max z
  46433. */
  46434. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46435. return 1;
  46436. };
  46437. __decorate([
  46438. BABYLON.serialize()
  46439. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46440. __decorate([
  46441. BABYLON.serialize()
  46442. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46443. __decorate([
  46444. BABYLON.serialize()
  46445. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46446. return DirectionalLight;
  46447. }(BABYLON.ShadowLight));
  46448. BABYLON.DirectionalLight = DirectionalLight;
  46449. })(BABYLON || (BABYLON = {}));
  46450. //# sourceMappingURL=babylon.directionalLight.js.map
  46451. "use strict";
  46452. var BABYLON;
  46453. (function (BABYLON) {
  46454. /**
  46455. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46456. * These values define a cone of light starting from the position, emitting toward the direction.
  46457. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46458. * and the exponent defines the speed of the decay of the light with distance (reach).
  46459. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46460. */
  46461. var SpotLight = /** @class */ (function (_super) {
  46462. __extends(SpotLight, _super);
  46463. /**
  46464. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46465. * It can cast shadows.
  46466. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46467. * @param name The light friendly name
  46468. * @param position The position of the spot light in the scene
  46469. * @param direction The direction of the light in the scene
  46470. * @param angle The cone angle of the light in Radians
  46471. * @param exponent The light decay speed with the distance from the emission spot
  46472. * @param scene The scene the lights belongs to
  46473. */
  46474. function SpotLight(name, position, direction, angle, exponent, scene) {
  46475. var _this = _super.call(this, name, scene) || this;
  46476. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46477. _this._projectionTextureLightNear = 1e-6;
  46478. _this._projectionTextureLightFar = 1000.0;
  46479. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46480. _this._projectionTextureViewLightDirty = true;
  46481. _this._projectionTextureProjectionLightDirty = true;
  46482. _this._projectionTextureDirty = true;
  46483. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46484. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46485. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46486. _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
  46487. _this.position = position;
  46488. _this.direction = direction;
  46489. _this.angle = angle;
  46490. _this.exponent = exponent;
  46491. return _this;
  46492. }
  46493. Object.defineProperty(SpotLight.prototype, "angle", {
  46494. /**
  46495. * Gets the cone angle of the spot light in Radians.
  46496. */
  46497. get: function () {
  46498. return this._angle;
  46499. },
  46500. /**
  46501. * Sets the cone angle of the spot light in Radians.
  46502. */
  46503. set: function (value) {
  46504. this._angle = value;
  46505. this._projectionTextureProjectionLightDirty = true;
  46506. this.forceProjectionMatrixCompute();
  46507. },
  46508. enumerable: true,
  46509. configurable: true
  46510. });
  46511. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46512. /**
  46513. * Allows scaling the angle of the light for shadow generation only.
  46514. */
  46515. get: function () {
  46516. return this._shadowAngleScale;
  46517. },
  46518. /**
  46519. * Allows scaling the angle of the light for shadow generation only.
  46520. */
  46521. set: function (value) {
  46522. this._shadowAngleScale = value;
  46523. this.forceProjectionMatrixCompute();
  46524. },
  46525. enumerable: true,
  46526. configurable: true
  46527. });
  46528. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46529. /**
  46530. * Allows reading the projecton texture
  46531. */
  46532. get: function () {
  46533. return this._projectionTextureMatrix;
  46534. },
  46535. enumerable: true,
  46536. configurable: true
  46537. });
  46538. ;
  46539. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46540. /**
  46541. * Gets the near clip of the Spotlight for texture projection.
  46542. */
  46543. get: function () {
  46544. return this._projectionTextureLightNear;
  46545. },
  46546. /**
  46547. * Sets the near clip of the Spotlight for texture projection.
  46548. */
  46549. set: function (value) {
  46550. this._projectionTextureLightNear = value;
  46551. this._projectionTextureProjectionLightDirty = true;
  46552. },
  46553. enumerable: true,
  46554. configurable: true
  46555. });
  46556. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46557. /**
  46558. * Gets the far clip of the Spotlight for texture projection.
  46559. */
  46560. get: function () {
  46561. return this._projectionTextureLightFar;
  46562. },
  46563. /**
  46564. * Sets the far clip of the Spotlight for texture projection.
  46565. */
  46566. set: function (value) {
  46567. this._projectionTextureLightFar = value;
  46568. this._projectionTextureProjectionLightDirty = true;
  46569. },
  46570. enumerable: true,
  46571. configurable: true
  46572. });
  46573. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46574. /**
  46575. * Gets the Up vector of the Spotlight for texture projection.
  46576. */
  46577. get: function () {
  46578. return this._projectionTextureUpDirection;
  46579. },
  46580. /**
  46581. * Sets the Up vector of the Spotlight for texture projection.
  46582. */
  46583. set: function (value) {
  46584. this._projectionTextureUpDirection = value;
  46585. this._projectionTextureProjectionLightDirty = true;
  46586. },
  46587. enumerable: true,
  46588. configurable: true
  46589. });
  46590. ;
  46591. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46592. /**
  46593. * Gets the projection texture of the light.
  46594. */
  46595. get: function () {
  46596. return this._projectionTexture;
  46597. },
  46598. /**
  46599. * Sets the projection texture of the light.
  46600. */
  46601. set: function (value) {
  46602. this._projectionTexture = value;
  46603. this._projectionTextureDirty = true;
  46604. },
  46605. enumerable: true,
  46606. configurable: true
  46607. });
  46608. /**
  46609. * Returns the string "SpotLight".
  46610. * @returns the class name
  46611. */
  46612. SpotLight.prototype.getClassName = function () {
  46613. return "SpotLight";
  46614. };
  46615. /**
  46616. * Returns the integer 2.
  46617. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46618. */
  46619. SpotLight.prototype.getTypeID = function () {
  46620. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46621. };
  46622. /**
  46623. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46624. */
  46625. SpotLight.prototype._setDirection = function (value) {
  46626. _super.prototype._setDirection.call(this, value);
  46627. this._projectionTextureViewLightDirty = true;
  46628. };
  46629. /**
  46630. * Overrides the position setter to recompute the projection texture view light Matrix.
  46631. */
  46632. SpotLight.prototype._setPosition = function (value) {
  46633. _super.prototype._setPosition.call(this, value);
  46634. this._projectionTextureViewLightDirty = true;
  46635. };
  46636. /**
  46637. * 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.
  46638. * Returns the SpotLight.
  46639. */
  46640. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46641. var activeCamera = this.getScene().activeCamera;
  46642. if (!activeCamera) {
  46643. return;
  46644. }
  46645. this._shadowAngleScale = this._shadowAngleScale || 1;
  46646. var angle = this._shadowAngleScale * this._angle;
  46647. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46648. };
  46649. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46650. this._projectionTextureViewLightDirty = false;
  46651. this._projectionTextureDirty = true;
  46652. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46653. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46654. };
  46655. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46656. this._projectionTextureProjectionLightDirty = false;
  46657. this._projectionTextureDirty = true;
  46658. var light_far = this.projectionTextureLightFar;
  46659. var light_near = this.projectionTextureLightNear;
  46660. var P = light_far / (light_far - light_near);
  46661. var Q = -P * light_near;
  46662. var S = 1.0 / Math.tan(this._angle / 2.0);
  46663. var A = 1.0;
  46664. BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
  46665. };
  46666. /**
  46667. * Main function for light texture projection matrix computing.
  46668. */
  46669. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46670. this._projectionTextureDirty = false;
  46671. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46672. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46673. };
  46674. SpotLight.prototype._buildUniformLayout = function () {
  46675. this._uniformBuffer.addUniform("vLightData", 4);
  46676. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46677. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46678. this._uniformBuffer.addUniform("vLightDirection", 3);
  46679. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46680. this._uniformBuffer.addUniform("depthValues", 2);
  46681. this._uniformBuffer.create();
  46682. };
  46683. /**
  46684. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46685. * @param effect The effect to update
  46686. * @param lightIndex The index of the light in the effect to update
  46687. * @returns The spot light
  46688. */
  46689. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46690. var normalizeDirection;
  46691. if (this.computeTransformedInformation()) {
  46692. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46693. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46694. }
  46695. else {
  46696. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46697. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46698. }
  46699. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46700. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46701. if (this._projectionTextureViewLightDirty) {
  46702. this._computeProjectionTextureViewLightMatrix();
  46703. }
  46704. if (this._projectionTextureProjectionLightDirty) {
  46705. this._computeProjectionTextureProjectionLightMatrix();
  46706. }
  46707. if (this._projectionTextureDirty) {
  46708. this._computeProjectionTextureMatrix();
  46709. }
  46710. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46711. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46712. }
  46713. return this;
  46714. };
  46715. /**
  46716. * Disposes the light and the associated resources.
  46717. */
  46718. SpotLight.prototype.dispose = function () {
  46719. _super.prototype.dispose.call(this);
  46720. if (this._projectionTexture) {
  46721. this._projectionTexture.dispose();
  46722. }
  46723. };
  46724. __decorate([
  46725. BABYLON.serialize()
  46726. ], SpotLight.prototype, "angle", null);
  46727. __decorate([
  46728. BABYLON.serialize()
  46729. ], SpotLight.prototype, "shadowAngleScale", null);
  46730. __decorate([
  46731. BABYLON.serialize()
  46732. ], SpotLight.prototype, "exponent", void 0);
  46733. __decorate([
  46734. BABYLON.serialize()
  46735. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46736. __decorate([
  46737. BABYLON.serialize()
  46738. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46739. __decorate([
  46740. BABYLON.serialize()
  46741. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46742. __decorate([
  46743. BABYLON.serializeAsTexture("projectedLightTexture")
  46744. ], SpotLight.prototype, "_projectionTexture", void 0);
  46745. return SpotLight;
  46746. }(BABYLON.ShadowLight));
  46747. BABYLON.SpotLight = SpotLight;
  46748. })(BABYLON || (BABYLON = {}));
  46749. //# sourceMappingURL=babylon.spotLight.js.map
  46750. "use strict";
  46751. var BABYLON;
  46752. (function (BABYLON) {
  46753. /**
  46754. * Class used to override all child animations of a given target
  46755. */
  46756. var AnimationPropertiesOverride = /** @class */ (function () {
  46757. function AnimationPropertiesOverride() {
  46758. /**
  46759. * Gets or sets a value indicating if animation blending must be used
  46760. */
  46761. this.enableBlending = false;
  46762. /**
  46763. * Gets or sets the blending speed to use when enableBlending is true
  46764. */
  46765. this.blendingSpeed = 0.01;
  46766. /**
  46767. * Gets or sets the default loop mode to use
  46768. */
  46769. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46770. }
  46771. return AnimationPropertiesOverride;
  46772. }());
  46773. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46774. })(BABYLON || (BABYLON = {}));
  46775. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46776. "use strict";
  46777. var BABYLON;
  46778. (function (BABYLON) {
  46779. var AnimationRange = /** @class */ (function () {
  46780. function AnimationRange(name, from, to) {
  46781. this.name = name;
  46782. this.from = from;
  46783. this.to = to;
  46784. }
  46785. AnimationRange.prototype.clone = function () {
  46786. return new AnimationRange(this.name, this.from, this.to);
  46787. };
  46788. return AnimationRange;
  46789. }());
  46790. BABYLON.AnimationRange = AnimationRange;
  46791. /**
  46792. * Composed of a frame, and an action function
  46793. */
  46794. var AnimationEvent = /** @class */ (function () {
  46795. function AnimationEvent(frame, action, onlyOnce) {
  46796. this.frame = frame;
  46797. this.action = action;
  46798. this.onlyOnce = onlyOnce;
  46799. this.isDone = false;
  46800. }
  46801. return AnimationEvent;
  46802. }());
  46803. BABYLON.AnimationEvent = AnimationEvent;
  46804. var PathCursor = /** @class */ (function () {
  46805. function PathCursor(path) {
  46806. this.path = path;
  46807. this._onchange = new Array();
  46808. this.value = 0;
  46809. this.animations = new Array();
  46810. }
  46811. PathCursor.prototype.getPoint = function () {
  46812. var point = this.path.getPointAtLengthPosition(this.value);
  46813. return new BABYLON.Vector3(point.x, 0, point.y);
  46814. };
  46815. PathCursor.prototype.moveAhead = function (step) {
  46816. if (step === void 0) { step = 0.002; }
  46817. this.move(step);
  46818. return this;
  46819. };
  46820. PathCursor.prototype.moveBack = function (step) {
  46821. if (step === void 0) { step = 0.002; }
  46822. this.move(-step);
  46823. return this;
  46824. };
  46825. PathCursor.prototype.move = function (step) {
  46826. if (Math.abs(step) > 1) {
  46827. throw "step size should be less than 1.";
  46828. }
  46829. this.value += step;
  46830. this.ensureLimits();
  46831. this.raiseOnChange();
  46832. return this;
  46833. };
  46834. PathCursor.prototype.ensureLimits = function () {
  46835. while (this.value > 1) {
  46836. this.value -= 1;
  46837. }
  46838. while (this.value < 0) {
  46839. this.value += 1;
  46840. }
  46841. return this;
  46842. };
  46843. // used by animation engine
  46844. PathCursor.prototype.raiseOnChange = function () {
  46845. var _this = this;
  46846. this._onchange.forEach(function (f) { return f(_this); });
  46847. return this;
  46848. };
  46849. PathCursor.prototype.onchange = function (f) {
  46850. this._onchange.push(f);
  46851. return this;
  46852. };
  46853. return PathCursor;
  46854. }());
  46855. BABYLON.PathCursor = PathCursor;
  46856. var AnimationKeyInterpolation;
  46857. (function (AnimationKeyInterpolation) {
  46858. /**
  46859. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46860. */
  46861. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46862. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46863. var Animation = /** @class */ (function () {
  46864. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46865. this.name = name;
  46866. this.targetProperty = targetProperty;
  46867. this.framePerSecond = framePerSecond;
  46868. this.dataType = dataType;
  46869. this.loopMode = loopMode;
  46870. this.enableBlending = enableBlending;
  46871. this._runtimeAnimations = new Array();
  46872. // The set of event that will be linked to this animation
  46873. this._events = new Array();
  46874. this.blendingSpeed = 0.01;
  46875. this._ranges = {};
  46876. this.targetPropertyPath = targetProperty.split(".");
  46877. this.dataType = dataType;
  46878. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46879. }
  46880. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46881. var dataType = undefined;
  46882. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46883. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46884. }
  46885. else if (from instanceof BABYLON.Quaternion) {
  46886. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46887. }
  46888. else if (from instanceof BABYLON.Vector3) {
  46889. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46890. }
  46891. else if (from instanceof BABYLON.Vector2) {
  46892. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46893. }
  46894. else if (from instanceof BABYLON.Color3) {
  46895. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46896. }
  46897. else if (from instanceof BABYLON.Size) {
  46898. dataType = Animation.ANIMATIONTYPE_SIZE;
  46899. }
  46900. if (dataType == undefined) {
  46901. return null;
  46902. }
  46903. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46904. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46905. animation.setKeys(keys);
  46906. if (easingFunction !== undefined) {
  46907. animation.setEasingFunction(easingFunction);
  46908. }
  46909. return animation;
  46910. };
  46911. /**
  46912. * Sets up an animation.
  46913. * @param property the property to animate
  46914. * @param animationType the animation type to apply
  46915. * @param easingFunction the easing function used in the animation
  46916. * @returns The created animation
  46917. */
  46918. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46919. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46920. animation.setEasingFunction(easingFunction);
  46921. return animation;
  46922. };
  46923. /**
  46924. * Create and start an animation on a node
  46925. * @param {string} name defines the name of the global animation that will be run on all nodes
  46926. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46927. * @param {string} targetProperty defines property to animate
  46928. * @param {number} framePerSecond defines the number of frame per second yo use
  46929. * @param {number} totalFrame defines the number of frames in total
  46930. * @param {any} from defines the initial value
  46931. * @param {any} to defines the final value
  46932. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46933. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46934. * @param onAnimationEnd defines the callback to call when animation end
  46935. * @returns the animatable created for this animation
  46936. */
  46937. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46938. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46939. if (!animation) {
  46940. return null;
  46941. }
  46942. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46943. };
  46944. /**
  46945. * Create and start an animation on a node and its descendants
  46946. * @param {string} name defines the name of the global animation that will be run on all nodes
  46947. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46948. * @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.
  46949. * @param {string} targetProperty defines property to animate
  46950. * @param {number} framePerSecond defines the number of frame per second yo use
  46951. * @param {number} totalFrame defines the number of frames in total
  46952. * @param {any} from defines the initial value
  46953. * @param {any} to defines the final value
  46954. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46955. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46956. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46957. * @returns the list of animatables created for all nodes
  46958. * @example https://www.babylonjs-playground.com/#MH0VLI
  46959. */
  46960. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46961. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46962. if (!animation) {
  46963. return null;
  46964. }
  46965. var scene = node.getScene();
  46966. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46967. };
  46968. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46969. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46970. if (!animation) {
  46971. return null;
  46972. }
  46973. node.animations.push(animation);
  46974. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46975. };
  46976. /**
  46977. * Transition property of the Camera to the target Value.
  46978. * @param property The property to transition
  46979. * @param targetValue The target Value of the property
  46980. * @param host The object where the property to animate belongs
  46981. * @param scene Scene used to run the animation
  46982. * @param frameRate Framerate (in frame/s) to use
  46983. * @param transition The transition type we want to use
  46984. * @param duration The duration of the animation, in milliseconds
  46985. * @param onAnimationEnd Call back trigger at the end of the animation.
  46986. */
  46987. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46988. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46989. if (duration <= 0) {
  46990. host[property] = targetValue;
  46991. if (onAnimationEnd) {
  46992. onAnimationEnd();
  46993. }
  46994. return null;
  46995. }
  46996. var endFrame = frameRate * (duration / 1000);
  46997. transition.setKeys([{
  46998. frame: 0,
  46999. value: host[property].clone ? host[property].clone() : host[property]
  47000. },
  47001. {
  47002. frame: endFrame,
  47003. value: targetValue
  47004. }]);
  47005. if (!host.animations) {
  47006. host.animations = [];
  47007. }
  47008. host.animations.push(transition);
  47009. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47010. animation.onAnimationEnd = onAnimationEnd;
  47011. return animation;
  47012. };
  47013. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47014. /**
  47015. * Return the array of runtime animations currently using this animation
  47016. */
  47017. get: function () {
  47018. return this._runtimeAnimations;
  47019. },
  47020. enumerable: true,
  47021. configurable: true
  47022. });
  47023. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47024. get: function () {
  47025. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47026. var runtimeAnimation = _a[_i];
  47027. if (!runtimeAnimation.isStopped) {
  47028. return true;
  47029. }
  47030. }
  47031. return false;
  47032. },
  47033. enumerable: true,
  47034. configurable: true
  47035. });
  47036. // Methods
  47037. /**
  47038. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47039. */
  47040. Animation.prototype.toString = function (fullDetails) {
  47041. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47042. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47043. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47044. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47045. if (fullDetails) {
  47046. ret += ", Ranges: {";
  47047. var first = true;
  47048. for (var name in this._ranges) {
  47049. if (first) {
  47050. ret += ", ";
  47051. first = false;
  47052. }
  47053. ret += name;
  47054. }
  47055. ret += "}";
  47056. }
  47057. return ret;
  47058. };
  47059. /**
  47060. * Add an event to this animation.
  47061. */
  47062. Animation.prototype.addEvent = function (event) {
  47063. this._events.push(event);
  47064. };
  47065. /**
  47066. * Remove all events found at the given frame
  47067. * @param frame
  47068. */
  47069. Animation.prototype.removeEvents = function (frame) {
  47070. for (var index = 0; index < this._events.length; index++) {
  47071. if (this._events[index].frame === frame) {
  47072. this._events.splice(index, 1);
  47073. index--;
  47074. }
  47075. }
  47076. };
  47077. Animation.prototype.getEvents = function () {
  47078. return this._events;
  47079. };
  47080. Animation.prototype.createRange = function (name, from, to) {
  47081. // check name not already in use; could happen for bones after serialized
  47082. if (!this._ranges[name]) {
  47083. this._ranges[name] = new AnimationRange(name, from, to);
  47084. }
  47085. };
  47086. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47087. if (deleteFrames === void 0) { deleteFrames = true; }
  47088. var range = this._ranges[name];
  47089. if (!range) {
  47090. return;
  47091. }
  47092. if (deleteFrames) {
  47093. var from = range.from;
  47094. var to = range.to;
  47095. // this loop MUST go high to low for multiple splices to work
  47096. for (var key = this._keys.length - 1; key >= 0; key--) {
  47097. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47098. this._keys.splice(key, 1);
  47099. }
  47100. }
  47101. }
  47102. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47103. };
  47104. Animation.prototype.getRange = function (name) {
  47105. return this._ranges[name];
  47106. };
  47107. Animation.prototype.getKeys = function () {
  47108. return this._keys;
  47109. };
  47110. Animation.prototype.getHighestFrame = function () {
  47111. var ret = 0;
  47112. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47113. if (ret < this._keys[key].frame) {
  47114. ret = this._keys[key].frame;
  47115. }
  47116. }
  47117. return ret;
  47118. };
  47119. Animation.prototype.getEasingFunction = function () {
  47120. return this._easingFunction;
  47121. };
  47122. Animation.prototype.setEasingFunction = function (easingFunction) {
  47123. this._easingFunction = easingFunction;
  47124. };
  47125. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47126. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47127. };
  47128. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47129. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47130. };
  47131. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47132. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47133. };
  47134. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47135. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47136. };
  47137. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47138. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47139. };
  47140. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47141. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47142. };
  47143. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47144. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47145. };
  47146. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47147. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47148. };
  47149. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47150. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47151. };
  47152. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47153. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47154. };
  47155. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47156. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47157. };
  47158. Animation.prototype.clone = function () {
  47159. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47160. clone.enableBlending = this.enableBlending;
  47161. clone.blendingSpeed = this.blendingSpeed;
  47162. if (this._keys) {
  47163. clone.setKeys(this._keys);
  47164. }
  47165. if (this._ranges) {
  47166. clone._ranges = {};
  47167. for (var name in this._ranges) {
  47168. var range = this._ranges[name];
  47169. if (!range) {
  47170. continue;
  47171. }
  47172. clone._ranges[name] = range.clone();
  47173. }
  47174. }
  47175. return clone;
  47176. };
  47177. Animation.prototype.setKeys = function (values) {
  47178. this._keys = values.slice(0);
  47179. };
  47180. Animation.prototype.serialize = function () {
  47181. var serializationObject = {};
  47182. serializationObject.name = this.name;
  47183. serializationObject.property = this.targetProperty;
  47184. serializationObject.framePerSecond = this.framePerSecond;
  47185. serializationObject.dataType = this.dataType;
  47186. serializationObject.loopBehavior = this.loopMode;
  47187. serializationObject.enableBlending = this.enableBlending;
  47188. serializationObject.blendingSpeed = this.blendingSpeed;
  47189. var dataType = this.dataType;
  47190. serializationObject.keys = [];
  47191. var keys = this.getKeys();
  47192. for (var index = 0; index < keys.length; index++) {
  47193. var animationKey = keys[index];
  47194. var key = {};
  47195. key.frame = animationKey.frame;
  47196. switch (dataType) {
  47197. case Animation.ANIMATIONTYPE_FLOAT:
  47198. key.values = [animationKey.value];
  47199. break;
  47200. case Animation.ANIMATIONTYPE_QUATERNION:
  47201. case Animation.ANIMATIONTYPE_MATRIX:
  47202. case Animation.ANIMATIONTYPE_VECTOR3:
  47203. case Animation.ANIMATIONTYPE_COLOR3:
  47204. key.values = animationKey.value.asArray();
  47205. break;
  47206. }
  47207. serializationObject.keys.push(key);
  47208. }
  47209. serializationObject.ranges = [];
  47210. for (var name in this._ranges) {
  47211. var source = this._ranges[name];
  47212. if (!source) {
  47213. continue;
  47214. }
  47215. var range = {};
  47216. range.name = name;
  47217. range.from = source.from;
  47218. range.to = source.to;
  47219. serializationObject.ranges.push(range);
  47220. }
  47221. return serializationObject;
  47222. };
  47223. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47224. get: function () {
  47225. return Animation._ANIMATIONTYPE_FLOAT;
  47226. },
  47227. enumerable: true,
  47228. configurable: true
  47229. });
  47230. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47231. get: function () {
  47232. return Animation._ANIMATIONTYPE_VECTOR3;
  47233. },
  47234. enumerable: true,
  47235. configurable: true
  47236. });
  47237. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47238. get: function () {
  47239. return Animation._ANIMATIONTYPE_VECTOR2;
  47240. },
  47241. enumerable: true,
  47242. configurable: true
  47243. });
  47244. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47245. get: function () {
  47246. return Animation._ANIMATIONTYPE_SIZE;
  47247. },
  47248. enumerable: true,
  47249. configurable: true
  47250. });
  47251. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47252. get: function () {
  47253. return Animation._ANIMATIONTYPE_QUATERNION;
  47254. },
  47255. enumerable: true,
  47256. configurable: true
  47257. });
  47258. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47259. get: function () {
  47260. return Animation._ANIMATIONTYPE_MATRIX;
  47261. },
  47262. enumerable: true,
  47263. configurable: true
  47264. });
  47265. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47266. get: function () {
  47267. return Animation._ANIMATIONTYPE_COLOR3;
  47268. },
  47269. enumerable: true,
  47270. configurable: true
  47271. });
  47272. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47273. get: function () {
  47274. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47275. },
  47276. enumerable: true,
  47277. configurable: true
  47278. });
  47279. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47280. get: function () {
  47281. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47282. },
  47283. enumerable: true,
  47284. configurable: true
  47285. });
  47286. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47287. get: function () {
  47288. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47289. },
  47290. enumerable: true,
  47291. configurable: true
  47292. });
  47293. Animation.Parse = function (parsedAnimation) {
  47294. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47295. var dataType = parsedAnimation.dataType;
  47296. var keys = [];
  47297. var data;
  47298. var index;
  47299. if (parsedAnimation.enableBlending) {
  47300. animation.enableBlending = parsedAnimation.enableBlending;
  47301. }
  47302. if (parsedAnimation.blendingSpeed) {
  47303. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47304. }
  47305. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47306. var key = parsedAnimation.keys[index];
  47307. var inTangent;
  47308. var outTangent;
  47309. switch (dataType) {
  47310. case Animation.ANIMATIONTYPE_FLOAT:
  47311. data = key.values[0];
  47312. if (key.values.length >= 1) {
  47313. inTangent = key.values[1];
  47314. }
  47315. if (key.values.length >= 2) {
  47316. outTangent = key.values[2];
  47317. }
  47318. break;
  47319. case Animation.ANIMATIONTYPE_QUATERNION:
  47320. data = BABYLON.Quaternion.FromArray(key.values);
  47321. if (key.values.length >= 8) {
  47322. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47323. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47324. inTangent = _inTangent;
  47325. }
  47326. }
  47327. if (key.values.length >= 12) {
  47328. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47329. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47330. outTangent = _outTangent;
  47331. }
  47332. }
  47333. break;
  47334. case Animation.ANIMATIONTYPE_MATRIX:
  47335. data = BABYLON.Matrix.FromArray(key.values);
  47336. break;
  47337. case Animation.ANIMATIONTYPE_COLOR3:
  47338. data = BABYLON.Color3.FromArray(key.values);
  47339. break;
  47340. case Animation.ANIMATIONTYPE_VECTOR3:
  47341. default:
  47342. data = BABYLON.Vector3.FromArray(key.values);
  47343. break;
  47344. }
  47345. var keyData = {};
  47346. keyData.frame = key.frame;
  47347. keyData.value = data;
  47348. if (inTangent != undefined) {
  47349. keyData.inTangent = inTangent;
  47350. }
  47351. if (outTangent != undefined) {
  47352. keyData.outTangent = outTangent;
  47353. }
  47354. keys.push(keyData);
  47355. }
  47356. animation.setKeys(keys);
  47357. if (parsedAnimation.ranges) {
  47358. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47359. data = parsedAnimation.ranges[index];
  47360. animation.createRange(data.name, data.from, data.to);
  47361. }
  47362. }
  47363. return animation;
  47364. };
  47365. Animation.AppendSerializedAnimations = function (source, destination) {
  47366. if (source.animations) {
  47367. destination.animations = [];
  47368. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47369. var animation = source.animations[animationIndex];
  47370. destination.animations.push(animation.serialize());
  47371. }
  47372. }
  47373. };
  47374. Animation.AllowMatricesInterpolation = false;
  47375. // Statics
  47376. Animation._ANIMATIONTYPE_FLOAT = 0;
  47377. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47378. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47379. Animation._ANIMATIONTYPE_MATRIX = 3;
  47380. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47381. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47382. Animation._ANIMATIONTYPE_SIZE = 6;
  47383. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47384. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47385. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47386. return Animation;
  47387. }());
  47388. BABYLON.Animation = Animation;
  47389. })(BABYLON || (BABYLON = {}));
  47390. //# sourceMappingURL=babylon.animation.js.map
  47391. "use strict";
  47392. var BABYLON;
  47393. (function (BABYLON) {
  47394. /**
  47395. * This class defines the direct association between an animation and a target
  47396. */
  47397. var TargetedAnimation = /** @class */ (function () {
  47398. function TargetedAnimation() {
  47399. }
  47400. return TargetedAnimation;
  47401. }());
  47402. BABYLON.TargetedAnimation = TargetedAnimation;
  47403. /**
  47404. * Use this class to create coordinated animations on multiple targets
  47405. */
  47406. var AnimationGroup = /** @class */ (function () {
  47407. function AnimationGroup(name, scene) {
  47408. if (scene === void 0) { scene = null; }
  47409. this.name = name;
  47410. this._targetedAnimations = new Array();
  47411. this._animatables = new Array();
  47412. this._from = Number.MAX_VALUE;
  47413. this._to = -Number.MAX_VALUE;
  47414. this._speedRatio = 1;
  47415. this.onAnimationEndObservable = new BABYLON.Observable();
  47416. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47417. this._scene.animationGroups.push(this);
  47418. }
  47419. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47420. /**
  47421. * Define if the animations are started
  47422. */
  47423. get: function () {
  47424. return this._isStarted;
  47425. },
  47426. enumerable: true,
  47427. configurable: true
  47428. });
  47429. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47430. /**
  47431. * Gets or sets the speed ratio to use for all animations
  47432. */
  47433. get: function () {
  47434. return this._speedRatio;
  47435. },
  47436. /**
  47437. * Gets or sets the speed ratio to use for all animations
  47438. */
  47439. set: function (value) {
  47440. if (this._speedRatio === value) {
  47441. return;
  47442. }
  47443. this._speedRatio = value;
  47444. for (var index = 0; index < this._animatables.length; index++) {
  47445. var animatable = this._animatables[index];
  47446. animatable.speedRatio = this._speedRatio;
  47447. }
  47448. },
  47449. enumerable: true,
  47450. configurable: true
  47451. });
  47452. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47453. /**
  47454. * Gets the targeted animations for this animation group
  47455. */
  47456. get: function () {
  47457. return this._targetedAnimations;
  47458. },
  47459. enumerable: true,
  47460. configurable: true
  47461. });
  47462. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47463. /**
  47464. * returning the list of animatables controlled by this animation group.
  47465. */
  47466. get: function () {
  47467. return this._animatables;
  47468. },
  47469. enumerable: true,
  47470. configurable: true
  47471. });
  47472. /**
  47473. * Add an animation (with its target) in the group
  47474. * @param animation defines the animation we want to add
  47475. * @param target defines the target of the animation
  47476. * @returns the {BABYLON.TargetedAnimation} object
  47477. */
  47478. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47479. var targetedAnimation = {
  47480. animation: animation,
  47481. target: target
  47482. };
  47483. var keys = animation.getKeys();
  47484. if (this._from > keys[0].frame) {
  47485. this._from = keys[0].frame;
  47486. }
  47487. if (this._to < keys[keys.length - 1].frame) {
  47488. this._to = keys[keys.length - 1].frame;
  47489. }
  47490. this._targetedAnimations.push(targetedAnimation);
  47491. return targetedAnimation;
  47492. };
  47493. /**
  47494. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47495. * It can add constant keys at begin or end
  47496. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47497. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47498. */
  47499. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47500. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47501. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47502. beginFrame = Math.max(beginFrame, this._from);
  47503. endFrame = Math.min(endFrame, this._to);
  47504. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47505. var targetedAnimation = this._targetedAnimations[index];
  47506. var keys = targetedAnimation.animation.getKeys();
  47507. var startKey = keys[0];
  47508. var endKey = keys[keys.length - 1];
  47509. if (startKey.frame > beginFrame) {
  47510. var newKey = {
  47511. frame: beginFrame,
  47512. value: startKey.value,
  47513. inTangent: startKey.inTangent,
  47514. outTangent: startKey.outTangent,
  47515. interpolation: startKey.interpolation
  47516. };
  47517. keys.splice(0, 0, newKey);
  47518. }
  47519. if (endKey.frame < endFrame) {
  47520. var newKey = {
  47521. frame: endFrame,
  47522. value: endKey.value,
  47523. inTangent: endKey.outTangent,
  47524. outTangent: endKey.outTangent,
  47525. interpolation: endKey.interpolation
  47526. };
  47527. keys.push(newKey);
  47528. }
  47529. }
  47530. return this;
  47531. };
  47532. /**
  47533. * Start all animations on given targets
  47534. * @param loop defines if animations must loop
  47535. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47536. */
  47537. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47538. var _this = this;
  47539. if (loop === void 0) { loop = false; }
  47540. if (speedRatio === void 0) { speedRatio = 1; }
  47541. if (this._isStarted || this._targetedAnimations.length === 0) {
  47542. return this;
  47543. }
  47544. var _loop_1 = function () {
  47545. var targetedAnimation = this_1._targetedAnimations[index];
  47546. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47547. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47548. }));
  47549. };
  47550. var this_1 = this;
  47551. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47552. _loop_1();
  47553. }
  47554. this._speedRatio = speedRatio;
  47555. this._isStarted = true;
  47556. return this;
  47557. };
  47558. /**
  47559. * Pause all animations
  47560. */
  47561. AnimationGroup.prototype.pause = function () {
  47562. if (!this._isStarted) {
  47563. return this;
  47564. }
  47565. for (var index = 0; index < this._animatables.length; index++) {
  47566. var animatable = this._animatables[index];
  47567. animatable.pause();
  47568. }
  47569. return this;
  47570. };
  47571. /**
  47572. * Play all animations to initial state
  47573. * This function will start() the animations if they were not started or will restart() them if they were paused
  47574. * @param loop defines if animations must loop
  47575. */
  47576. AnimationGroup.prototype.play = function (loop) {
  47577. if (this.isStarted) {
  47578. if (loop !== undefined) {
  47579. for (var index = 0; index < this._animatables.length; index++) {
  47580. var animatable = this._animatables[index];
  47581. animatable.loopAnimation = loop;
  47582. }
  47583. }
  47584. this.restart();
  47585. }
  47586. else {
  47587. this.start(loop, this._speedRatio);
  47588. }
  47589. return this;
  47590. };
  47591. /**
  47592. * Reset all animations to initial state
  47593. */
  47594. AnimationGroup.prototype.reset = function () {
  47595. if (!this._isStarted) {
  47596. return this;
  47597. }
  47598. for (var index = 0; index < this._animatables.length; index++) {
  47599. var animatable = this._animatables[index];
  47600. animatable.reset();
  47601. }
  47602. return this;
  47603. };
  47604. /**
  47605. * Restart animations from key 0
  47606. */
  47607. AnimationGroup.prototype.restart = function () {
  47608. if (!this._isStarted) {
  47609. return this;
  47610. }
  47611. for (var index = 0; index < this._animatables.length; index++) {
  47612. var animatable = this._animatables[index];
  47613. animatable.restart();
  47614. }
  47615. return this;
  47616. };
  47617. /**
  47618. * Stop all animations
  47619. */
  47620. AnimationGroup.prototype.stop = function () {
  47621. if (!this._isStarted) {
  47622. return this;
  47623. }
  47624. for (var index = 0; index < this._animatables.length; index++) {
  47625. var animatable = this._animatables[index];
  47626. animatable.stop();
  47627. }
  47628. this._isStarted = false;
  47629. return this;
  47630. };
  47631. /**
  47632. * Goes to a specific frame in this animation group
  47633. *
  47634. * @param frame the frame number to go to
  47635. * @return the animationGroup
  47636. */
  47637. AnimationGroup.prototype.goToFrame = function (frame) {
  47638. if (!this._isStarted) {
  47639. return this;
  47640. }
  47641. for (var index = 0; index < this._animatables.length; index++) {
  47642. var animatable = this._animatables[index];
  47643. animatable.goToFrame(frame);
  47644. }
  47645. return this;
  47646. };
  47647. /**
  47648. * Dispose all associated resources
  47649. */
  47650. AnimationGroup.prototype.dispose = function () {
  47651. this._targetedAnimations = [];
  47652. this._animatables = [];
  47653. var index = this._scene.animationGroups.indexOf(this);
  47654. if (index > -1) {
  47655. this._scene.animationGroups.splice(index, 1);
  47656. }
  47657. };
  47658. return AnimationGroup;
  47659. }());
  47660. BABYLON.AnimationGroup = AnimationGroup;
  47661. })(BABYLON || (BABYLON = {}));
  47662. //# sourceMappingURL=babylon.animationGroup.js.map
  47663. "use strict";
  47664. var BABYLON;
  47665. (function (BABYLON) {
  47666. var RuntimeAnimation = /** @class */ (function () {
  47667. /**
  47668. * Create a new RuntimeAnimation object
  47669. * @param target defines the target of the animation
  47670. * @param animation defines the source {BABYLON.Animation} object
  47671. * @param scene defines the hosting scene
  47672. */
  47673. function RuntimeAnimation(target, animation, scene) {
  47674. this.currentFrame = 0;
  47675. this._offsetsCache = {};
  47676. this._highLimitsCache = {};
  47677. this._stopped = false;
  47678. this._blendingFactor = 0;
  47679. this._targetPath = "";
  47680. this._weight = 1.0;
  47681. this._ratioOffset = 0;
  47682. this._previousDelay = 0;
  47683. this._previousRatio = 0;
  47684. this._animation = animation;
  47685. this._target = target;
  47686. this._scene = scene;
  47687. animation._runtimeAnimations.push(this);
  47688. }
  47689. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47690. /**
  47691. * Gets the weight of the runtime animation
  47692. */
  47693. get: function () {
  47694. return this._weight;
  47695. },
  47696. enumerable: true,
  47697. configurable: true
  47698. });
  47699. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47700. /**
  47701. * Gets the original value of the runtime animation
  47702. */
  47703. get: function () {
  47704. return this._originalValue;
  47705. },
  47706. enumerable: true,
  47707. configurable: true
  47708. });
  47709. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47710. /**
  47711. * Gets the current value of the runtime animation
  47712. */
  47713. get: function () {
  47714. return this._currentValue;
  47715. },
  47716. enumerable: true,
  47717. configurable: true
  47718. });
  47719. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47720. /**
  47721. * Gets the path where to store the animated value in the target
  47722. */
  47723. get: function () {
  47724. return this._targetPath;
  47725. },
  47726. enumerable: true,
  47727. configurable: true
  47728. });
  47729. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47730. /**
  47731. * Gets the actual target of the runtime animation
  47732. */
  47733. get: function () {
  47734. return this._activeTarget;
  47735. },
  47736. enumerable: true,
  47737. configurable: true
  47738. });
  47739. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47740. get: function () {
  47741. return this._animation;
  47742. },
  47743. enumerable: true,
  47744. configurable: true
  47745. });
  47746. RuntimeAnimation.prototype.reset = function () {
  47747. this._offsetsCache = {};
  47748. this._highLimitsCache = {};
  47749. this.currentFrame = 0;
  47750. this._blendingFactor = 0;
  47751. this._originalValue = null;
  47752. };
  47753. RuntimeAnimation.prototype.isStopped = function () {
  47754. return this._stopped;
  47755. };
  47756. RuntimeAnimation.prototype.dispose = function () {
  47757. var index = this._animation.runtimeAnimations.indexOf(this);
  47758. if (index > -1) {
  47759. this._animation.runtimeAnimations.splice(index, 1);
  47760. }
  47761. };
  47762. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47763. if (typeof value === "function") {
  47764. return value();
  47765. }
  47766. return value;
  47767. };
  47768. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47769. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47770. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47771. }
  47772. this.currentFrame = currentFrame;
  47773. var keys = this._animation.getKeys();
  47774. // Try to get a hash to find the right key
  47775. 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));
  47776. if (keys[startKeyIndex].frame >= currentFrame) {
  47777. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47778. startKeyIndex--;
  47779. }
  47780. }
  47781. for (var key = startKeyIndex; key < keys.length; key++) {
  47782. var endKey = keys[key + 1];
  47783. if (endKey.frame >= currentFrame) {
  47784. var startKey = keys[key];
  47785. var startValue = this._getKeyValue(startKey.value);
  47786. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47787. return startValue;
  47788. }
  47789. var endValue = this._getKeyValue(endKey.value);
  47790. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47791. var frameDelta = endKey.frame - startKey.frame;
  47792. // gradient : percent of currentFrame between the frame inf and the frame sup
  47793. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47794. // check for easingFunction and correction of gradient
  47795. var easingFunction = this._animation.getEasingFunction();
  47796. if (easingFunction != null) {
  47797. gradient = easingFunction.ease(gradient);
  47798. }
  47799. switch (this._animation.dataType) {
  47800. // Float
  47801. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47802. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47803. switch (loopMode) {
  47804. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47805. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47806. return floatValue;
  47807. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47808. return offsetValue * repeatCount + floatValue;
  47809. }
  47810. break;
  47811. // Quaternion
  47812. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47813. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47814. switch (loopMode) {
  47815. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47816. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47817. return quatValue;
  47818. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47819. return quatValue.add(offsetValue.scale(repeatCount));
  47820. }
  47821. return quatValue;
  47822. // Vector3
  47823. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47824. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47825. switch (loopMode) {
  47826. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47827. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47828. return vec3Value;
  47829. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47830. return vec3Value.add(offsetValue.scale(repeatCount));
  47831. }
  47832. // Vector2
  47833. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47834. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47835. switch (loopMode) {
  47836. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47837. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47838. return vec2Value;
  47839. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47840. return vec2Value.add(offsetValue.scale(repeatCount));
  47841. }
  47842. // Size
  47843. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47844. switch (loopMode) {
  47845. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47846. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47847. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47848. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47849. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47850. }
  47851. // Color3
  47852. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47853. switch (loopMode) {
  47854. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47855. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47856. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47857. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47858. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47859. }
  47860. // Matrix
  47861. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47862. switch (loopMode) {
  47863. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47864. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47865. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47866. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47867. }
  47868. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47869. return startValue;
  47870. }
  47871. default:
  47872. break;
  47873. }
  47874. break;
  47875. }
  47876. }
  47877. return this._getKeyValue(keys[keys.length - 1].value);
  47878. };
  47879. /**
  47880. * Affect the interpolated value to the target
  47881. * @param currentValue defines the value computed by the animation
  47882. * @param weight defines the weight to apply to this value
  47883. */
  47884. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47885. if (weight === void 0) { weight = 1.0; }
  47886. // Set value
  47887. var path;
  47888. var destination;
  47889. var targetPropertyPath = this._animation.targetPropertyPath;
  47890. if (targetPropertyPath.length > 1) {
  47891. var property = this._target[targetPropertyPath[0]];
  47892. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47893. property = property[targetPropertyPath[index]];
  47894. }
  47895. path = [targetPropertyPath.length - 1];
  47896. destination = property;
  47897. }
  47898. else {
  47899. path = targetPropertyPath[0];
  47900. destination = this._target;
  47901. }
  47902. this._targetPath = path;
  47903. this._activeTarget = destination;
  47904. this._weight = weight;
  47905. // Blending
  47906. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47907. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47908. if (enableBlending && this._blendingFactor <= 1.0) {
  47909. if (!this._originalBlendValue) {
  47910. var originalValue = destination[path];
  47911. if (originalValue.clone) {
  47912. this._originalBlendValue = originalValue.clone();
  47913. }
  47914. else {
  47915. this._originalBlendValue = originalValue;
  47916. }
  47917. }
  47918. }
  47919. if (weight !== -1.0) {
  47920. if (!this._originalValue) {
  47921. var originalValue = void 0;
  47922. if (destination.getRestPose) {
  47923. originalValue = destination.getRestPose();
  47924. }
  47925. else {
  47926. originalValue = destination[path];
  47927. }
  47928. if (originalValue.clone) {
  47929. this._originalValue = originalValue.clone();
  47930. }
  47931. else {
  47932. this._originalValue = originalValue;
  47933. }
  47934. }
  47935. }
  47936. if (enableBlending && this._blendingFactor <= 1.0) {
  47937. if (this._originalBlendValue.prototype) {
  47938. if (this._originalBlendValue.prototype.Lerp) {
  47939. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47940. }
  47941. else {
  47942. this._currentValue = currentValue;
  47943. }
  47944. }
  47945. else if (this._originalBlendValue.m) {
  47946. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47947. }
  47948. else {
  47949. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47950. }
  47951. this._blendingFactor += blendingSpeed;
  47952. }
  47953. else {
  47954. this._currentValue = currentValue;
  47955. }
  47956. if (weight !== -1.0) {
  47957. this._scene._registerTargetForLateAnimationBinding(this);
  47958. }
  47959. else {
  47960. destination[path] = this._currentValue;
  47961. }
  47962. if (this._target.markAsDirty) {
  47963. this._target.markAsDirty(this._animation.targetProperty);
  47964. }
  47965. };
  47966. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47967. if (this._target && this._target.animationPropertiesOverride) {
  47968. return this._target.animationPropertiesOverride.loopMode;
  47969. }
  47970. return this._animation.loopMode;
  47971. };
  47972. /**
  47973. * Move the current animation to a given frame
  47974. * @param frame defines the frame to move to
  47975. */
  47976. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47977. var keys = this._animation.getKeys();
  47978. if (frame < keys[0].frame) {
  47979. frame = keys[0].frame;
  47980. }
  47981. else if (frame > keys[keys.length - 1].frame) {
  47982. frame = keys[keys.length - 1].frame;
  47983. }
  47984. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47985. this.setValue(currentValue, -1);
  47986. };
  47987. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47988. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47989. this._ratioOffset = this._previousRatio - newRatio;
  47990. };
  47991. /**
  47992. * Execute the current animation
  47993. * @param delay defines the delay to add to the current frame
  47994. * @param from defines the lower bound of the animation range
  47995. * @param to defines the upper bound of the animation range
  47996. * @param loop defines if the current animation must loop
  47997. * @param speedRatio defines the current speed ratio
  47998. * @param weight defines the weight of the animation (default is -1 so no weight)
  47999. * @returns a boolean indicating if the animation has ended
  48000. */
  48001. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48002. if (weight === void 0) { weight = -1.0; }
  48003. var targetPropertyPath = this._animation.targetPropertyPath;
  48004. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48005. this._stopped = true;
  48006. return false;
  48007. }
  48008. var returnValue = true;
  48009. var keys = this._animation.getKeys();
  48010. // Adding a start key at frame 0 if missing
  48011. if (keys[0].frame !== 0) {
  48012. var newKey = { frame: 0, value: keys[0].value };
  48013. keys.splice(0, 0, newKey);
  48014. }
  48015. // Check limits
  48016. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48017. from = keys[0].frame;
  48018. }
  48019. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48020. to = keys[keys.length - 1].frame;
  48021. }
  48022. //to and from cannot be the same key
  48023. if (from === to) {
  48024. if (from > keys[0].frame) {
  48025. from--;
  48026. }
  48027. else if (to < keys[keys.length - 1].frame) {
  48028. to++;
  48029. }
  48030. }
  48031. // Compute ratio
  48032. var range = to - from;
  48033. var offsetValue;
  48034. // ratio represents the frame delta between from and to
  48035. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48036. var highLimitValue = 0;
  48037. this._previousDelay = delay;
  48038. this._previousRatio = ratio;
  48039. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48040. returnValue = false;
  48041. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48042. }
  48043. else {
  48044. // Get max value if required
  48045. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48046. var keyOffset = to.toString() + from.toString();
  48047. if (!this._offsetsCache[keyOffset]) {
  48048. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48049. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48050. switch (this._animation.dataType) {
  48051. // Float
  48052. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48053. this._offsetsCache[keyOffset] = toValue - fromValue;
  48054. break;
  48055. // Quaternion
  48056. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48057. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48058. break;
  48059. // Vector3
  48060. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48061. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48062. // Vector2
  48063. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48064. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48065. // Size
  48066. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48067. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48068. // Color3
  48069. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48070. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48071. default:
  48072. break;
  48073. }
  48074. this._highLimitsCache[keyOffset] = toValue;
  48075. }
  48076. highLimitValue = this._highLimitsCache[keyOffset];
  48077. offsetValue = this._offsetsCache[keyOffset];
  48078. }
  48079. }
  48080. if (offsetValue === undefined) {
  48081. switch (this._animation.dataType) {
  48082. // Float
  48083. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48084. offsetValue = 0;
  48085. break;
  48086. // Quaternion
  48087. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48088. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48089. break;
  48090. // Vector3
  48091. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48092. offsetValue = BABYLON.Vector3.Zero();
  48093. break;
  48094. // Vector2
  48095. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48096. offsetValue = BABYLON.Vector2.Zero();
  48097. break;
  48098. // Size
  48099. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48100. offsetValue = BABYLON.Size.Zero();
  48101. break;
  48102. // Color3
  48103. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48104. offsetValue = BABYLON.Color3.Black();
  48105. }
  48106. }
  48107. // Compute value
  48108. var repeatCount = (ratio / range) >> 0;
  48109. var currentFrame = returnValue ? from + ratio % range : to;
  48110. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48111. // Set value
  48112. this.setValue(currentValue, weight);
  48113. // Check events
  48114. var events = this._animation.getEvents();
  48115. for (var index = 0; index < events.length; index++) {
  48116. // Make sure current frame has passed event frame and that event frame is within the current range
  48117. // Also, handle both forward and reverse animations
  48118. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48119. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48120. var event = events[index];
  48121. if (!event.isDone) {
  48122. // If event should be done only once, remove it.
  48123. if (event.onlyOnce) {
  48124. events.splice(index, 1);
  48125. index--;
  48126. }
  48127. event.isDone = true;
  48128. event.action();
  48129. } // Don't do anything if the event has already be done.
  48130. }
  48131. else if (events[index].isDone && !events[index].onlyOnce) {
  48132. // reset event, the animation is looping
  48133. events[index].isDone = false;
  48134. }
  48135. }
  48136. if (!returnValue) {
  48137. this._stopped = true;
  48138. }
  48139. return returnValue;
  48140. };
  48141. return RuntimeAnimation;
  48142. }());
  48143. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48144. })(BABYLON || (BABYLON = {}));
  48145. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48146. "use strict";
  48147. var BABYLON;
  48148. (function (BABYLON) {
  48149. var Animatable = /** @class */ (function () {
  48150. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48151. if (fromFrame === void 0) { fromFrame = 0; }
  48152. if (toFrame === void 0) { toFrame = 100; }
  48153. if (loopAnimation === void 0) { loopAnimation = false; }
  48154. if (speedRatio === void 0) { speedRatio = 1.0; }
  48155. this.target = target;
  48156. this.fromFrame = fromFrame;
  48157. this.toFrame = toFrame;
  48158. this.loopAnimation = loopAnimation;
  48159. this.onAnimationEnd = onAnimationEnd;
  48160. this._localDelayOffset = null;
  48161. this._pausedDelay = null;
  48162. this._runtimeAnimations = new Array();
  48163. this._paused = false;
  48164. this._speedRatio = 1;
  48165. this._weight = -1.0;
  48166. this.animationStarted = false;
  48167. if (animations) {
  48168. this.appendAnimations(target, animations);
  48169. }
  48170. this._speedRatio = speedRatio;
  48171. this._scene = scene;
  48172. scene._activeAnimatables.push(this);
  48173. }
  48174. Object.defineProperty(Animatable.prototype, "weight", {
  48175. /**
  48176. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48177. */
  48178. get: function () {
  48179. return this._weight;
  48180. },
  48181. set: function (value) {
  48182. if (value === -1) {
  48183. this._weight = -1;
  48184. return;
  48185. }
  48186. // Else weight must be in [0, 1] range
  48187. this._weight = Math.min(Math.max(value, 0), 1.0);
  48188. },
  48189. enumerable: true,
  48190. configurable: true
  48191. });
  48192. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48193. /**
  48194. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48195. */
  48196. get: function () {
  48197. return this._speedRatio;
  48198. },
  48199. set: function (value) {
  48200. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48201. var animation = this._runtimeAnimations[index];
  48202. animation._prepareForSpeedRatioChange(value);
  48203. }
  48204. this._speedRatio = value;
  48205. },
  48206. enumerable: true,
  48207. configurable: true
  48208. });
  48209. // Methods
  48210. Animatable.prototype.getAnimations = function () {
  48211. return this._runtimeAnimations;
  48212. };
  48213. Animatable.prototype.appendAnimations = function (target, animations) {
  48214. for (var index = 0; index < animations.length; index++) {
  48215. var animation = animations[index];
  48216. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene));
  48217. }
  48218. };
  48219. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48220. var runtimeAnimations = this._runtimeAnimations;
  48221. for (var index = 0; index < runtimeAnimations.length; index++) {
  48222. if (runtimeAnimations[index].animation.targetProperty === property) {
  48223. return runtimeAnimations[index].animation;
  48224. }
  48225. }
  48226. return null;
  48227. };
  48228. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48229. var runtimeAnimations = this._runtimeAnimations;
  48230. for (var index = 0; index < runtimeAnimations.length; index++) {
  48231. if (runtimeAnimations[index].animation.targetProperty === property) {
  48232. return runtimeAnimations[index];
  48233. }
  48234. }
  48235. return null;
  48236. };
  48237. Animatable.prototype.reset = function () {
  48238. var runtimeAnimations = this._runtimeAnimations;
  48239. for (var index = 0; index < runtimeAnimations.length; index++) {
  48240. runtimeAnimations[index].reset();
  48241. }
  48242. // Reset to original value
  48243. for (index = 0; index < runtimeAnimations.length; index++) {
  48244. var animation = runtimeAnimations[index];
  48245. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48246. }
  48247. this._localDelayOffset = null;
  48248. this._pausedDelay = null;
  48249. };
  48250. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48251. var runtimeAnimations = this._runtimeAnimations;
  48252. for (var index = 0; index < runtimeAnimations.length; index++) {
  48253. runtimeAnimations[index].animation.enableBlending = true;
  48254. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48255. }
  48256. };
  48257. Animatable.prototype.disableBlending = function () {
  48258. var runtimeAnimations = this._runtimeAnimations;
  48259. for (var index = 0; index < runtimeAnimations.length; index++) {
  48260. runtimeAnimations[index].animation.enableBlending = false;
  48261. }
  48262. };
  48263. Animatable.prototype.goToFrame = function (frame) {
  48264. var runtimeAnimations = this._runtimeAnimations;
  48265. if (runtimeAnimations[0]) {
  48266. var fps = runtimeAnimations[0].animation.framePerSecond;
  48267. var currentFrame = runtimeAnimations[0].currentFrame;
  48268. var adjustTime = frame - currentFrame;
  48269. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48270. if (this._localDelayOffset === null) {
  48271. this._localDelayOffset = 0;
  48272. }
  48273. this._localDelayOffset -= delay;
  48274. }
  48275. for (var index = 0; index < runtimeAnimations.length; index++) {
  48276. runtimeAnimations[index].goToFrame(frame);
  48277. }
  48278. };
  48279. Animatable.prototype.pause = function () {
  48280. if (this._paused) {
  48281. return;
  48282. }
  48283. this._paused = true;
  48284. };
  48285. Animatable.prototype.restart = function () {
  48286. this._paused = false;
  48287. };
  48288. Animatable.prototype.stop = function (animationName) {
  48289. if (animationName) {
  48290. var idx = this._scene._activeAnimatables.indexOf(this);
  48291. if (idx > -1) {
  48292. var runtimeAnimations = this._runtimeAnimations;
  48293. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48294. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48295. continue;
  48296. }
  48297. runtimeAnimations[index].dispose();
  48298. runtimeAnimations.splice(index, 1);
  48299. }
  48300. if (runtimeAnimations.length == 0) {
  48301. this._scene._activeAnimatables.splice(idx, 1);
  48302. if (this.onAnimationEnd) {
  48303. this.onAnimationEnd();
  48304. }
  48305. }
  48306. }
  48307. }
  48308. else {
  48309. var index = this._scene._activeAnimatables.indexOf(this);
  48310. if (index > -1) {
  48311. this._scene._activeAnimatables.splice(index, 1);
  48312. var runtimeAnimations = this._runtimeAnimations;
  48313. for (var index = 0; index < runtimeAnimations.length; index++) {
  48314. runtimeAnimations[index].dispose();
  48315. }
  48316. if (this.onAnimationEnd) {
  48317. this.onAnimationEnd();
  48318. }
  48319. }
  48320. }
  48321. };
  48322. Animatable.prototype._animate = function (delay) {
  48323. if (this._paused) {
  48324. this.animationStarted = false;
  48325. if (this._pausedDelay === null) {
  48326. this._pausedDelay = delay;
  48327. }
  48328. return true;
  48329. }
  48330. if (this._localDelayOffset === null) {
  48331. this._localDelayOffset = delay;
  48332. this._pausedDelay = null;
  48333. }
  48334. else if (this._pausedDelay !== null) {
  48335. this._localDelayOffset += delay - this._pausedDelay;
  48336. this._pausedDelay = null;
  48337. }
  48338. if (this._weight === 0) {
  48339. return true;
  48340. }
  48341. // Animating
  48342. var running = false;
  48343. var runtimeAnimations = this._runtimeAnimations;
  48344. var index;
  48345. for (index = 0; index < runtimeAnimations.length; index++) {
  48346. var animation = runtimeAnimations[index];
  48347. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48348. running = running || isRunning;
  48349. }
  48350. this.animationStarted = running;
  48351. if (!running) {
  48352. // Remove from active animatables
  48353. index = this._scene._activeAnimatables.indexOf(this);
  48354. this._scene._activeAnimatables.splice(index, 1);
  48355. // Dispose all runtime animations
  48356. for (index = 0; index < runtimeAnimations.length; index++) {
  48357. runtimeAnimations[index].dispose();
  48358. }
  48359. }
  48360. if (!running && this.onAnimationEnd) {
  48361. this.onAnimationEnd();
  48362. this.onAnimationEnd = null;
  48363. }
  48364. return running;
  48365. };
  48366. return Animatable;
  48367. }());
  48368. BABYLON.Animatable = Animatable;
  48369. })(BABYLON || (BABYLON = {}));
  48370. //# sourceMappingURL=babylon.animatable.js.map
  48371. "use strict";
  48372. var BABYLON;
  48373. (function (BABYLON) {
  48374. var EasingFunction = /** @class */ (function () {
  48375. function EasingFunction() {
  48376. // Properties
  48377. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48378. }
  48379. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48380. get: function () {
  48381. return EasingFunction._EASINGMODE_EASEIN;
  48382. },
  48383. enumerable: true,
  48384. configurable: true
  48385. });
  48386. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48387. get: function () {
  48388. return EasingFunction._EASINGMODE_EASEOUT;
  48389. },
  48390. enumerable: true,
  48391. configurable: true
  48392. });
  48393. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48394. get: function () {
  48395. return EasingFunction._EASINGMODE_EASEINOUT;
  48396. },
  48397. enumerable: true,
  48398. configurable: true
  48399. });
  48400. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48401. var n = Math.min(Math.max(easingMode, 0), 2);
  48402. this._easingMode = n;
  48403. };
  48404. EasingFunction.prototype.getEasingMode = function () {
  48405. return this._easingMode;
  48406. };
  48407. EasingFunction.prototype.easeInCore = function (gradient) {
  48408. throw new Error('You must implement this method');
  48409. };
  48410. EasingFunction.prototype.ease = function (gradient) {
  48411. switch (this._easingMode) {
  48412. case EasingFunction.EASINGMODE_EASEIN:
  48413. return this.easeInCore(gradient);
  48414. case EasingFunction.EASINGMODE_EASEOUT:
  48415. return (1 - this.easeInCore(1 - gradient));
  48416. }
  48417. if (gradient >= 0.5) {
  48418. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48419. }
  48420. return (this.easeInCore(gradient * 2) * 0.5);
  48421. };
  48422. //Statics
  48423. EasingFunction._EASINGMODE_EASEIN = 0;
  48424. EasingFunction._EASINGMODE_EASEOUT = 1;
  48425. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48426. return EasingFunction;
  48427. }());
  48428. BABYLON.EasingFunction = EasingFunction;
  48429. var CircleEase = /** @class */ (function (_super) {
  48430. __extends(CircleEase, _super);
  48431. function CircleEase() {
  48432. return _super !== null && _super.apply(this, arguments) || this;
  48433. }
  48434. CircleEase.prototype.easeInCore = function (gradient) {
  48435. gradient = Math.max(0, Math.min(1, gradient));
  48436. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48437. };
  48438. return CircleEase;
  48439. }(EasingFunction));
  48440. BABYLON.CircleEase = CircleEase;
  48441. var BackEase = /** @class */ (function (_super) {
  48442. __extends(BackEase, _super);
  48443. function BackEase(amplitude) {
  48444. if (amplitude === void 0) { amplitude = 1; }
  48445. var _this = _super.call(this) || this;
  48446. _this.amplitude = amplitude;
  48447. return _this;
  48448. }
  48449. BackEase.prototype.easeInCore = function (gradient) {
  48450. var num = Math.max(0, this.amplitude);
  48451. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48452. };
  48453. return BackEase;
  48454. }(EasingFunction));
  48455. BABYLON.BackEase = BackEase;
  48456. var BounceEase = /** @class */ (function (_super) {
  48457. __extends(BounceEase, _super);
  48458. function BounceEase(bounces, bounciness) {
  48459. if (bounces === void 0) { bounces = 3; }
  48460. if (bounciness === void 0) { bounciness = 2; }
  48461. var _this = _super.call(this) || this;
  48462. _this.bounces = bounces;
  48463. _this.bounciness = bounciness;
  48464. return _this;
  48465. }
  48466. BounceEase.prototype.easeInCore = function (gradient) {
  48467. var y = Math.max(0.0, this.bounces);
  48468. var bounciness = this.bounciness;
  48469. if (bounciness <= 1.0) {
  48470. bounciness = 1.001;
  48471. }
  48472. var num9 = Math.pow(bounciness, y);
  48473. var num5 = 1.0 - bounciness;
  48474. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48475. var num15 = gradient * num4;
  48476. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48477. var num3 = Math.floor(num65);
  48478. var num13 = num3 + 1.0;
  48479. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48480. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48481. var num7 = (num8 + num12) * 0.5;
  48482. var num6 = gradient - num7;
  48483. var num2 = num7 - num8;
  48484. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48485. };
  48486. return BounceEase;
  48487. }(EasingFunction));
  48488. BABYLON.BounceEase = BounceEase;
  48489. var CubicEase = /** @class */ (function (_super) {
  48490. __extends(CubicEase, _super);
  48491. function CubicEase() {
  48492. return _super !== null && _super.apply(this, arguments) || this;
  48493. }
  48494. CubicEase.prototype.easeInCore = function (gradient) {
  48495. return (gradient * gradient * gradient);
  48496. };
  48497. return CubicEase;
  48498. }(EasingFunction));
  48499. BABYLON.CubicEase = CubicEase;
  48500. var ElasticEase = /** @class */ (function (_super) {
  48501. __extends(ElasticEase, _super);
  48502. function ElasticEase(oscillations, springiness) {
  48503. if (oscillations === void 0) { oscillations = 3; }
  48504. if (springiness === void 0) { springiness = 3; }
  48505. var _this = _super.call(this) || this;
  48506. _this.oscillations = oscillations;
  48507. _this.springiness = springiness;
  48508. return _this;
  48509. }
  48510. ElasticEase.prototype.easeInCore = function (gradient) {
  48511. var num2;
  48512. var num3 = Math.max(0.0, this.oscillations);
  48513. var num = Math.max(0.0, this.springiness);
  48514. if (num == 0) {
  48515. num2 = gradient;
  48516. }
  48517. else {
  48518. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48519. }
  48520. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48521. };
  48522. return ElasticEase;
  48523. }(EasingFunction));
  48524. BABYLON.ElasticEase = ElasticEase;
  48525. var ExponentialEase = /** @class */ (function (_super) {
  48526. __extends(ExponentialEase, _super);
  48527. function ExponentialEase(exponent) {
  48528. if (exponent === void 0) { exponent = 2; }
  48529. var _this = _super.call(this) || this;
  48530. _this.exponent = exponent;
  48531. return _this;
  48532. }
  48533. ExponentialEase.prototype.easeInCore = function (gradient) {
  48534. if (this.exponent <= 0) {
  48535. return gradient;
  48536. }
  48537. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48538. };
  48539. return ExponentialEase;
  48540. }(EasingFunction));
  48541. BABYLON.ExponentialEase = ExponentialEase;
  48542. var PowerEase = /** @class */ (function (_super) {
  48543. __extends(PowerEase, _super);
  48544. function PowerEase(power) {
  48545. if (power === void 0) { power = 2; }
  48546. var _this = _super.call(this) || this;
  48547. _this.power = power;
  48548. return _this;
  48549. }
  48550. PowerEase.prototype.easeInCore = function (gradient) {
  48551. var y = Math.max(0.0, this.power);
  48552. return Math.pow(gradient, y);
  48553. };
  48554. return PowerEase;
  48555. }(EasingFunction));
  48556. BABYLON.PowerEase = PowerEase;
  48557. var QuadraticEase = /** @class */ (function (_super) {
  48558. __extends(QuadraticEase, _super);
  48559. function QuadraticEase() {
  48560. return _super !== null && _super.apply(this, arguments) || this;
  48561. }
  48562. QuadraticEase.prototype.easeInCore = function (gradient) {
  48563. return (gradient * gradient);
  48564. };
  48565. return QuadraticEase;
  48566. }(EasingFunction));
  48567. BABYLON.QuadraticEase = QuadraticEase;
  48568. var QuarticEase = /** @class */ (function (_super) {
  48569. __extends(QuarticEase, _super);
  48570. function QuarticEase() {
  48571. return _super !== null && _super.apply(this, arguments) || this;
  48572. }
  48573. QuarticEase.prototype.easeInCore = function (gradient) {
  48574. return (gradient * gradient * gradient * gradient);
  48575. };
  48576. return QuarticEase;
  48577. }(EasingFunction));
  48578. BABYLON.QuarticEase = QuarticEase;
  48579. var QuinticEase = /** @class */ (function (_super) {
  48580. __extends(QuinticEase, _super);
  48581. function QuinticEase() {
  48582. return _super !== null && _super.apply(this, arguments) || this;
  48583. }
  48584. QuinticEase.prototype.easeInCore = function (gradient) {
  48585. return (gradient * gradient * gradient * gradient * gradient);
  48586. };
  48587. return QuinticEase;
  48588. }(EasingFunction));
  48589. BABYLON.QuinticEase = QuinticEase;
  48590. var SineEase = /** @class */ (function (_super) {
  48591. __extends(SineEase, _super);
  48592. function SineEase() {
  48593. return _super !== null && _super.apply(this, arguments) || this;
  48594. }
  48595. SineEase.prototype.easeInCore = function (gradient) {
  48596. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48597. };
  48598. return SineEase;
  48599. }(EasingFunction));
  48600. BABYLON.SineEase = SineEase;
  48601. var BezierCurveEase = /** @class */ (function (_super) {
  48602. __extends(BezierCurveEase, _super);
  48603. function BezierCurveEase(x1, y1, x2, y2) {
  48604. if (x1 === void 0) { x1 = 0; }
  48605. if (y1 === void 0) { y1 = 0; }
  48606. if (x2 === void 0) { x2 = 1; }
  48607. if (y2 === void 0) { y2 = 1; }
  48608. var _this = _super.call(this) || this;
  48609. _this.x1 = x1;
  48610. _this.y1 = y1;
  48611. _this.x2 = x2;
  48612. _this.y2 = y2;
  48613. return _this;
  48614. }
  48615. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48616. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48617. };
  48618. return BezierCurveEase;
  48619. }(EasingFunction));
  48620. BABYLON.BezierCurveEase = BezierCurveEase;
  48621. })(BABYLON || (BABYLON = {}));
  48622. //# sourceMappingURL=babylon.easing.js.map
  48623. "use strict";
  48624. var BABYLON;
  48625. (function (BABYLON) {
  48626. var Condition = /** @class */ (function () {
  48627. function Condition(actionManager) {
  48628. this._actionManager = actionManager;
  48629. }
  48630. Condition.prototype.isValid = function () {
  48631. return true;
  48632. };
  48633. Condition.prototype._getProperty = function (propertyPath) {
  48634. return this._actionManager._getProperty(propertyPath);
  48635. };
  48636. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48637. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48638. };
  48639. Condition.prototype.serialize = function () {
  48640. };
  48641. Condition.prototype._serialize = function (serializedCondition) {
  48642. return {
  48643. type: 2,
  48644. children: [],
  48645. name: serializedCondition.name,
  48646. properties: serializedCondition.properties
  48647. };
  48648. };
  48649. return Condition;
  48650. }());
  48651. BABYLON.Condition = Condition;
  48652. var ValueCondition = /** @class */ (function (_super) {
  48653. __extends(ValueCondition, _super);
  48654. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48655. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48656. var _this = _super.call(this, actionManager) || this;
  48657. _this.propertyPath = propertyPath;
  48658. _this.value = value;
  48659. _this.operator = operator;
  48660. _this._target = target;
  48661. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48662. _this._property = _this._getProperty(_this.propertyPath);
  48663. return _this;
  48664. }
  48665. Object.defineProperty(ValueCondition, "IsEqual", {
  48666. get: function () {
  48667. return ValueCondition._IsEqual;
  48668. },
  48669. enumerable: true,
  48670. configurable: true
  48671. });
  48672. Object.defineProperty(ValueCondition, "IsDifferent", {
  48673. get: function () {
  48674. return ValueCondition._IsDifferent;
  48675. },
  48676. enumerable: true,
  48677. configurable: true
  48678. });
  48679. Object.defineProperty(ValueCondition, "IsGreater", {
  48680. get: function () {
  48681. return ValueCondition._IsGreater;
  48682. },
  48683. enumerable: true,
  48684. configurable: true
  48685. });
  48686. Object.defineProperty(ValueCondition, "IsLesser", {
  48687. get: function () {
  48688. return ValueCondition._IsLesser;
  48689. },
  48690. enumerable: true,
  48691. configurable: true
  48692. });
  48693. // Methods
  48694. ValueCondition.prototype.isValid = function () {
  48695. switch (this.operator) {
  48696. case ValueCondition.IsGreater:
  48697. return this._effectiveTarget[this._property] > this.value;
  48698. case ValueCondition.IsLesser:
  48699. return this._effectiveTarget[this._property] < this.value;
  48700. case ValueCondition.IsEqual:
  48701. case ValueCondition.IsDifferent:
  48702. var check;
  48703. if (this.value.equals) {
  48704. check = this.value.equals(this._effectiveTarget[this._property]);
  48705. }
  48706. else {
  48707. check = this.value === this._effectiveTarget[this._property];
  48708. }
  48709. return this.operator === ValueCondition.IsEqual ? check : !check;
  48710. }
  48711. return false;
  48712. };
  48713. ValueCondition.prototype.serialize = function () {
  48714. return this._serialize({
  48715. name: "ValueCondition",
  48716. properties: [
  48717. BABYLON.Action._GetTargetProperty(this._target),
  48718. { name: "propertyPath", value: this.propertyPath },
  48719. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48720. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48721. ]
  48722. });
  48723. };
  48724. ValueCondition.GetOperatorName = function (operator) {
  48725. switch (operator) {
  48726. case ValueCondition._IsEqual: return "IsEqual";
  48727. case ValueCondition._IsDifferent: return "IsDifferent";
  48728. case ValueCondition._IsGreater: return "IsGreater";
  48729. case ValueCondition._IsLesser: return "IsLesser";
  48730. default: return "";
  48731. }
  48732. };
  48733. // Statics
  48734. ValueCondition._IsEqual = 0;
  48735. ValueCondition._IsDifferent = 1;
  48736. ValueCondition._IsGreater = 2;
  48737. ValueCondition._IsLesser = 3;
  48738. return ValueCondition;
  48739. }(Condition));
  48740. BABYLON.ValueCondition = ValueCondition;
  48741. var PredicateCondition = /** @class */ (function (_super) {
  48742. __extends(PredicateCondition, _super);
  48743. function PredicateCondition(actionManager, predicate) {
  48744. var _this = _super.call(this, actionManager) || this;
  48745. _this.predicate = predicate;
  48746. return _this;
  48747. }
  48748. PredicateCondition.prototype.isValid = function () {
  48749. return this.predicate();
  48750. };
  48751. return PredicateCondition;
  48752. }(Condition));
  48753. BABYLON.PredicateCondition = PredicateCondition;
  48754. var StateCondition = /** @class */ (function (_super) {
  48755. __extends(StateCondition, _super);
  48756. function StateCondition(actionManager, target, value) {
  48757. var _this = _super.call(this, actionManager) || this;
  48758. _this.value = value;
  48759. _this._target = target;
  48760. return _this;
  48761. }
  48762. // Methods
  48763. StateCondition.prototype.isValid = function () {
  48764. return this._target.state === this.value;
  48765. };
  48766. StateCondition.prototype.serialize = function () {
  48767. return this._serialize({
  48768. name: "StateCondition",
  48769. properties: [
  48770. BABYLON.Action._GetTargetProperty(this._target),
  48771. { name: "value", value: this.value }
  48772. ]
  48773. });
  48774. };
  48775. return StateCondition;
  48776. }(Condition));
  48777. BABYLON.StateCondition = StateCondition;
  48778. })(BABYLON || (BABYLON = {}));
  48779. //# sourceMappingURL=babylon.condition.js.map
  48780. "use strict";
  48781. var BABYLON;
  48782. (function (BABYLON) {
  48783. var Action = /** @class */ (function () {
  48784. function Action(triggerOptions, condition) {
  48785. this.triggerOptions = triggerOptions;
  48786. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48787. if (triggerOptions.parameter) {
  48788. this.trigger = triggerOptions.trigger;
  48789. this._triggerParameter = triggerOptions.parameter;
  48790. }
  48791. else {
  48792. this.trigger = triggerOptions;
  48793. }
  48794. this._nextActiveAction = this;
  48795. this._condition = condition;
  48796. }
  48797. // Methods
  48798. Action.prototype._prepare = function () {
  48799. };
  48800. Action.prototype.getTriggerParameter = function () {
  48801. return this._triggerParameter;
  48802. };
  48803. Action.prototype._executeCurrent = function (evt) {
  48804. if (this._nextActiveAction._condition) {
  48805. var condition = this._nextActiveAction._condition;
  48806. var currentRenderId = this._actionManager.getScene().getRenderId();
  48807. // We cache the current evaluation for the current frame
  48808. if (condition._evaluationId === currentRenderId) {
  48809. if (!condition._currentResult) {
  48810. return;
  48811. }
  48812. }
  48813. else {
  48814. condition._evaluationId = currentRenderId;
  48815. if (!condition.isValid()) {
  48816. condition._currentResult = false;
  48817. return;
  48818. }
  48819. condition._currentResult = true;
  48820. }
  48821. }
  48822. this.onBeforeExecuteObservable.notifyObservers(this);
  48823. this._nextActiveAction.execute(evt);
  48824. this.skipToNextActiveAction();
  48825. };
  48826. Action.prototype.execute = function (evt) {
  48827. };
  48828. Action.prototype.skipToNextActiveAction = function () {
  48829. if (this._nextActiveAction._child) {
  48830. if (!this._nextActiveAction._child._actionManager) {
  48831. this._nextActiveAction._child._actionManager = this._actionManager;
  48832. }
  48833. this._nextActiveAction = this._nextActiveAction._child;
  48834. }
  48835. else {
  48836. this._nextActiveAction = this;
  48837. }
  48838. };
  48839. Action.prototype.then = function (action) {
  48840. this._child = action;
  48841. action._actionManager = this._actionManager;
  48842. action._prepare();
  48843. return action;
  48844. };
  48845. Action.prototype._getProperty = function (propertyPath) {
  48846. return this._actionManager._getProperty(propertyPath);
  48847. };
  48848. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48849. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48850. };
  48851. Action.prototype.serialize = function (parent) {
  48852. };
  48853. // Called by BABYLON.Action objects in serialize(...). Internal use
  48854. Action.prototype._serialize = function (serializedAction, parent) {
  48855. var serializationObject = {
  48856. type: 1,
  48857. children: [],
  48858. name: serializedAction.name,
  48859. properties: serializedAction.properties || []
  48860. };
  48861. // Serialize child
  48862. if (this._child) {
  48863. this._child.serialize(serializationObject);
  48864. }
  48865. // Check if "this" has a condition
  48866. if (this._condition) {
  48867. var serializedCondition = this._condition.serialize();
  48868. serializedCondition.children.push(serializationObject);
  48869. if (parent) {
  48870. parent.children.push(serializedCondition);
  48871. }
  48872. return serializedCondition;
  48873. }
  48874. if (parent) {
  48875. parent.children.push(serializationObject);
  48876. }
  48877. return serializationObject;
  48878. };
  48879. Action._SerializeValueAsString = function (value) {
  48880. if (typeof value === "number") {
  48881. return value.toString();
  48882. }
  48883. if (typeof value === "boolean") {
  48884. return value ? "true" : "false";
  48885. }
  48886. if (value instanceof BABYLON.Vector2) {
  48887. return value.x + ", " + value.y;
  48888. }
  48889. if (value instanceof BABYLON.Vector3) {
  48890. return value.x + ", " + value.y + ", " + value.z;
  48891. }
  48892. if (value instanceof BABYLON.Color3) {
  48893. return value.r + ", " + value.g + ", " + value.b;
  48894. }
  48895. if (value instanceof BABYLON.Color4) {
  48896. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48897. }
  48898. return value; // string
  48899. };
  48900. Action._GetTargetProperty = function (target) {
  48901. return {
  48902. name: "target",
  48903. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48904. : target instanceof BABYLON.Light ? "LightProperties"
  48905. : target instanceof BABYLON.Camera ? "CameraProperties"
  48906. : "SceneProperties",
  48907. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48908. };
  48909. };
  48910. return Action;
  48911. }());
  48912. BABYLON.Action = Action;
  48913. })(BABYLON || (BABYLON = {}));
  48914. //# sourceMappingURL=babylon.action.js.map
  48915. "use strict";
  48916. var BABYLON;
  48917. (function (BABYLON) {
  48918. /**
  48919. * ActionEvent is the event beint sent when an action is triggered.
  48920. */
  48921. var ActionEvent = /** @class */ (function () {
  48922. /**
  48923. * @param source The mesh or sprite that triggered the action.
  48924. * @param pointerX The X mouse cursor position at the time of the event
  48925. * @param pointerY The Y mouse cursor position at the time of the event
  48926. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48927. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48928. */
  48929. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48930. this.source = source;
  48931. this.pointerX = pointerX;
  48932. this.pointerY = pointerY;
  48933. this.meshUnderPointer = meshUnderPointer;
  48934. this.sourceEvent = sourceEvent;
  48935. this.additionalData = additionalData;
  48936. }
  48937. /**
  48938. * Helper function to auto-create an ActionEvent from a source mesh.
  48939. * @param source The source mesh that triggered the event
  48940. * @param evt {Event} The original (browser) event
  48941. */
  48942. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48943. var scene = source.getScene();
  48944. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48945. };
  48946. /**
  48947. * Helper function to auto-create an ActionEvent from a source mesh.
  48948. * @param source The source sprite that triggered the event
  48949. * @param scene Scene associated with the sprite
  48950. * @param evt {Event} The original (browser) event
  48951. */
  48952. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48953. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48954. };
  48955. /**
  48956. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48957. * @param scene the scene where the event occurred
  48958. * @param evt {Event} The original (browser) event
  48959. */
  48960. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48961. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48962. };
  48963. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48964. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48965. };
  48966. return ActionEvent;
  48967. }());
  48968. BABYLON.ActionEvent = ActionEvent;
  48969. /**
  48970. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48971. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48972. */
  48973. var ActionManager = /** @class */ (function () {
  48974. function ActionManager(scene) {
  48975. // Members
  48976. this.actions = new Array();
  48977. this.hoverCursor = '';
  48978. this._scene = scene;
  48979. scene._actionManagers.push(this);
  48980. }
  48981. Object.defineProperty(ActionManager, "NothingTrigger", {
  48982. get: function () {
  48983. return ActionManager._NothingTrigger;
  48984. },
  48985. enumerable: true,
  48986. configurable: true
  48987. });
  48988. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48989. get: function () {
  48990. return ActionManager._OnPickTrigger;
  48991. },
  48992. enumerable: true,
  48993. configurable: true
  48994. });
  48995. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48996. get: function () {
  48997. return ActionManager._OnLeftPickTrigger;
  48998. },
  48999. enumerable: true,
  49000. configurable: true
  49001. });
  49002. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49003. get: function () {
  49004. return ActionManager._OnRightPickTrigger;
  49005. },
  49006. enumerable: true,
  49007. configurable: true
  49008. });
  49009. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49010. get: function () {
  49011. return ActionManager._OnCenterPickTrigger;
  49012. },
  49013. enumerable: true,
  49014. configurable: true
  49015. });
  49016. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49017. get: function () {
  49018. return ActionManager._OnPickDownTrigger;
  49019. },
  49020. enumerable: true,
  49021. configurable: true
  49022. });
  49023. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49024. get: function () {
  49025. return ActionManager._OnDoublePickTrigger;
  49026. },
  49027. enumerable: true,
  49028. configurable: true
  49029. });
  49030. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49031. get: function () {
  49032. return ActionManager._OnPickUpTrigger;
  49033. },
  49034. enumerable: true,
  49035. configurable: true
  49036. });
  49037. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49038. /// This trigger will only be raised if you also declared a OnPickDown
  49039. get: function () {
  49040. return ActionManager._OnPickOutTrigger;
  49041. },
  49042. enumerable: true,
  49043. configurable: true
  49044. });
  49045. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49046. get: function () {
  49047. return ActionManager._OnLongPressTrigger;
  49048. },
  49049. enumerable: true,
  49050. configurable: true
  49051. });
  49052. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49053. get: function () {
  49054. return ActionManager._OnPointerOverTrigger;
  49055. },
  49056. enumerable: true,
  49057. configurable: true
  49058. });
  49059. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49060. get: function () {
  49061. return ActionManager._OnPointerOutTrigger;
  49062. },
  49063. enumerable: true,
  49064. configurable: true
  49065. });
  49066. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49067. get: function () {
  49068. return ActionManager._OnEveryFrameTrigger;
  49069. },
  49070. enumerable: true,
  49071. configurable: true
  49072. });
  49073. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49074. get: function () {
  49075. return ActionManager._OnIntersectionEnterTrigger;
  49076. },
  49077. enumerable: true,
  49078. configurable: true
  49079. });
  49080. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49081. get: function () {
  49082. return ActionManager._OnIntersectionExitTrigger;
  49083. },
  49084. enumerable: true,
  49085. configurable: true
  49086. });
  49087. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49088. get: function () {
  49089. return ActionManager._OnKeyDownTrigger;
  49090. },
  49091. enumerable: true,
  49092. configurable: true
  49093. });
  49094. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49095. get: function () {
  49096. return ActionManager._OnKeyUpTrigger;
  49097. },
  49098. enumerable: true,
  49099. configurable: true
  49100. });
  49101. // Methods
  49102. ActionManager.prototype.dispose = function () {
  49103. var index = this._scene._actionManagers.indexOf(this);
  49104. for (var i = 0; i < this.actions.length; i++) {
  49105. var action = this.actions[i];
  49106. ActionManager.Triggers[action.trigger]--;
  49107. if (ActionManager.Triggers[action.trigger] === 0) {
  49108. delete ActionManager.Triggers[action.trigger];
  49109. }
  49110. }
  49111. if (index > -1) {
  49112. this._scene._actionManagers.splice(index, 1);
  49113. }
  49114. };
  49115. ActionManager.prototype.getScene = function () {
  49116. return this._scene;
  49117. };
  49118. /**
  49119. * Does this action manager handles actions of any of the given triggers
  49120. * @param {number[]} triggers - the triggers to be tested
  49121. * @return {boolean} whether one (or more) of the triggers is handeled
  49122. */
  49123. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49124. for (var index = 0; index < this.actions.length; index++) {
  49125. var action = this.actions[index];
  49126. if (triggers.indexOf(action.trigger) > -1) {
  49127. return true;
  49128. }
  49129. }
  49130. return false;
  49131. };
  49132. /**
  49133. * Does this action manager handles actions of a given trigger
  49134. * @param {number} trigger - the trigger to be tested
  49135. * @return {boolean} whether the trigger is handeled
  49136. */
  49137. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49138. for (var index = 0; index < this.actions.length; index++) {
  49139. var action = this.actions[index];
  49140. if (action.trigger === trigger) {
  49141. return true;
  49142. }
  49143. }
  49144. return false;
  49145. };
  49146. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49147. /**
  49148. * Does this action manager has pointer triggers
  49149. * @return {boolean} whether or not it has pointer triggers
  49150. */
  49151. get: function () {
  49152. for (var index = 0; index < this.actions.length; index++) {
  49153. var action = this.actions[index];
  49154. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49155. return true;
  49156. }
  49157. }
  49158. return false;
  49159. },
  49160. enumerable: true,
  49161. configurable: true
  49162. });
  49163. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49164. /**
  49165. * Does this action manager has pick triggers
  49166. * @return {boolean} whether or not it has pick triggers
  49167. */
  49168. get: function () {
  49169. for (var index = 0; index < this.actions.length; index++) {
  49170. var action = this.actions[index];
  49171. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49172. return true;
  49173. }
  49174. }
  49175. return false;
  49176. },
  49177. enumerable: true,
  49178. configurable: true
  49179. });
  49180. Object.defineProperty(ActionManager, "HasTriggers", {
  49181. /**
  49182. * Does exist one action manager with at least one trigger
  49183. * @return {boolean} whether or not it exists one action manager with one trigger
  49184. **/
  49185. get: function () {
  49186. for (var t in ActionManager.Triggers) {
  49187. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49188. return true;
  49189. }
  49190. }
  49191. return false;
  49192. },
  49193. enumerable: true,
  49194. configurable: true
  49195. });
  49196. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49197. /**
  49198. * Does exist one action manager with at least one pick trigger
  49199. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49200. **/
  49201. get: function () {
  49202. for (var t in ActionManager.Triggers) {
  49203. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49204. var t_int = parseInt(t);
  49205. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49206. return true;
  49207. }
  49208. }
  49209. }
  49210. return false;
  49211. },
  49212. enumerable: true,
  49213. configurable: true
  49214. });
  49215. /**
  49216. * Does exist one action manager that handles actions of a given trigger
  49217. * @param {number} trigger - the trigger to be tested
  49218. * @return {boolean} whether the trigger is handeled by at least one action manager
  49219. **/
  49220. ActionManager.HasSpecificTrigger = function (trigger) {
  49221. for (var t in ActionManager.Triggers) {
  49222. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49223. var t_int = parseInt(t);
  49224. if (t_int === trigger) {
  49225. return true;
  49226. }
  49227. }
  49228. }
  49229. return false;
  49230. };
  49231. /**
  49232. * Registers an action to this action manager
  49233. * @param {BABYLON.Action} action - the action to be registered
  49234. * @return {BABYLON.Action} the action amended (prepared) after registration
  49235. */
  49236. ActionManager.prototype.registerAction = function (action) {
  49237. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49238. if (this.getScene().actionManager !== this) {
  49239. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49240. return null;
  49241. }
  49242. }
  49243. this.actions.push(action);
  49244. if (ActionManager.Triggers[action.trigger]) {
  49245. ActionManager.Triggers[action.trigger]++;
  49246. }
  49247. else {
  49248. ActionManager.Triggers[action.trigger] = 1;
  49249. }
  49250. action._actionManager = this;
  49251. action._prepare();
  49252. return action;
  49253. };
  49254. /**
  49255. * Unregisters an action to this action manager
  49256. * @param action The action to be unregistered
  49257. * @return whether the action has been unregistered
  49258. */
  49259. ActionManager.prototype.unregisterAction = function (action) {
  49260. var index = this.actions.indexOf(action);
  49261. if (index !== -1) {
  49262. this.actions.splice(index, 1);
  49263. ActionManager.Triggers[action.trigger] -= 1;
  49264. if (ActionManager.Triggers[action.trigger] === 0) {
  49265. delete ActionManager.Triggers[action.trigger];
  49266. }
  49267. delete action._actionManager;
  49268. return true;
  49269. }
  49270. return false;
  49271. };
  49272. /**
  49273. * Process a specific trigger
  49274. * @param {number} trigger - the trigger to process
  49275. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49276. */
  49277. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49278. for (var index = 0; index < this.actions.length; index++) {
  49279. var action = this.actions[index];
  49280. if (action.trigger === trigger) {
  49281. if (evt) {
  49282. if (trigger === ActionManager.OnKeyUpTrigger
  49283. || trigger === ActionManager.OnKeyDownTrigger) {
  49284. var parameter = action.getTriggerParameter();
  49285. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49286. if (!parameter.toLowerCase) {
  49287. continue;
  49288. }
  49289. var lowerCase = parameter.toLowerCase();
  49290. if (lowerCase !== evt.sourceEvent.key) {
  49291. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49292. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49293. if (actualkey !== lowerCase) {
  49294. continue;
  49295. }
  49296. }
  49297. }
  49298. }
  49299. }
  49300. action._executeCurrent(evt);
  49301. }
  49302. }
  49303. };
  49304. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49305. var properties = propertyPath.split(".");
  49306. for (var index = 0; index < properties.length - 1; index++) {
  49307. target = target[properties[index]];
  49308. }
  49309. return target;
  49310. };
  49311. ActionManager.prototype._getProperty = function (propertyPath) {
  49312. var properties = propertyPath.split(".");
  49313. return properties[properties.length - 1];
  49314. };
  49315. ActionManager.prototype.serialize = function (name) {
  49316. var root = {
  49317. children: new Array(),
  49318. name: name,
  49319. type: 3,
  49320. properties: new Array() // Empty for root but required
  49321. };
  49322. for (var i = 0; i < this.actions.length; i++) {
  49323. var triggerObject = {
  49324. type: 0,
  49325. children: new Array(),
  49326. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49327. properties: new Array()
  49328. };
  49329. var triggerOptions = this.actions[i].triggerOptions;
  49330. if (triggerOptions && typeof triggerOptions !== "number") {
  49331. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49332. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49333. }
  49334. else {
  49335. var parameter = {};
  49336. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49337. if (triggerOptions.parameter.mesh) {
  49338. parameter._meshId = triggerOptions.parameter.mesh.id;
  49339. }
  49340. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49341. }
  49342. }
  49343. // Serialize child action, recursively
  49344. this.actions[i].serialize(triggerObject);
  49345. // Add serialized trigger
  49346. root.children.push(triggerObject);
  49347. }
  49348. return root;
  49349. };
  49350. ActionManager.Parse = function (parsedActions, object, scene) {
  49351. var actionManager = new ActionManager(scene);
  49352. if (object === null)
  49353. scene.actionManager = actionManager;
  49354. else
  49355. object.actionManager = actionManager;
  49356. // instanciate a new object
  49357. var instanciate = function (name, params) {
  49358. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49359. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49360. newInstance.constructor.apply(newInstance, params);
  49361. return newInstance;
  49362. };
  49363. var parseParameter = function (name, value, target, propertyPath) {
  49364. if (propertyPath === null) {
  49365. // String, boolean or float
  49366. var floatValue = parseFloat(value);
  49367. if (value === "true" || value === "false")
  49368. return value === "true";
  49369. else
  49370. return isNaN(floatValue) ? value : floatValue;
  49371. }
  49372. var effectiveTarget = propertyPath.split(".");
  49373. var values = value.split(",");
  49374. // Get effective Target
  49375. for (var i = 0; i < effectiveTarget.length; i++) {
  49376. target = target[effectiveTarget[i]];
  49377. }
  49378. // Return appropriate value with its type
  49379. if (typeof (target) === "boolean")
  49380. return values[0] === "true";
  49381. if (typeof (target) === "string")
  49382. return values[0];
  49383. // Parameters with multiple values such as Vector3 etc.
  49384. var split = new Array();
  49385. for (var i = 0; i < values.length; i++)
  49386. split.push(parseFloat(values[i]));
  49387. if (target instanceof BABYLON.Vector3)
  49388. return BABYLON.Vector3.FromArray(split);
  49389. if (target instanceof BABYLON.Vector4)
  49390. return BABYLON.Vector4.FromArray(split);
  49391. if (target instanceof BABYLON.Color3)
  49392. return BABYLON.Color3.FromArray(split);
  49393. if (target instanceof BABYLON.Color4)
  49394. return BABYLON.Color4.FromArray(split);
  49395. return parseFloat(values[0]);
  49396. };
  49397. // traverse graph per trigger
  49398. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49399. if (combineArray === void 0) { combineArray = null; }
  49400. if (parsedAction.detached)
  49401. return;
  49402. var parameters = new Array();
  49403. var target = null;
  49404. var propertyPath = null;
  49405. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49406. // Parameters
  49407. if (parsedAction.type === 2)
  49408. parameters.push(actionManager);
  49409. else
  49410. parameters.push(trigger);
  49411. if (combine) {
  49412. var actions = new Array();
  49413. for (var j = 0; j < parsedAction.combine.length; j++) {
  49414. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49415. }
  49416. parameters.push(actions);
  49417. }
  49418. else {
  49419. for (var i = 0; i < parsedAction.properties.length; i++) {
  49420. var value = parsedAction.properties[i].value;
  49421. var name = parsedAction.properties[i].name;
  49422. var targetType = parsedAction.properties[i].targetType;
  49423. if (name === "target")
  49424. if (targetType !== null && targetType === "SceneProperties")
  49425. value = target = scene;
  49426. else
  49427. value = target = scene.getNodeByName(value);
  49428. else if (name === "parent")
  49429. value = scene.getNodeByName(value);
  49430. else if (name === "sound")
  49431. value = scene.getSoundByName(value);
  49432. else if (name !== "propertyPath") {
  49433. if (parsedAction.type === 2 && name === "operator")
  49434. value = BABYLON.ValueCondition[value];
  49435. else
  49436. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49437. }
  49438. else {
  49439. propertyPath = value;
  49440. }
  49441. parameters.push(value);
  49442. }
  49443. }
  49444. if (combineArray === null) {
  49445. parameters.push(condition);
  49446. }
  49447. else {
  49448. parameters.push(null);
  49449. }
  49450. // If interpolate value action
  49451. if (parsedAction.name === "InterpolateValueAction") {
  49452. var param = parameters[parameters.length - 2];
  49453. parameters[parameters.length - 1] = param;
  49454. parameters[parameters.length - 2] = condition;
  49455. }
  49456. // Action or condition(s) and not CombineAction
  49457. var newAction = instanciate(parsedAction.name, parameters);
  49458. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49459. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49460. if (action)
  49461. action.then(nothing);
  49462. else
  49463. actionManager.registerAction(nothing);
  49464. action = nothing;
  49465. }
  49466. if (combineArray === null) {
  49467. if (newAction instanceof BABYLON.Condition) {
  49468. condition = newAction;
  49469. newAction = action;
  49470. }
  49471. else {
  49472. condition = null;
  49473. if (action)
  49474. action.then(newAction);
  49475. else
  49476. actionManager.registerAction(newAction);
  49477. }
  49478. }
  49479. else {
  49480. combineArray.push(newAction);
  49481. }
  49482. for (var i = 0; i < parsedAction.children.length; i++)
  49483. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49484. };
  49485. // triggers
  49486. for (var i = 0; i < parsedActions.children.length; i++) {
  49487. var triggerParams;
  49488. var trigger = parsedActions.children[i];
  49489. if (trigger.properties.length > 0) {
  49490. var param = trigger.properties[0].value;
  49491. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49492. if (value._meshId) {
  49493. value.mesh = scene.getMeshByID(value._meshId);
  49494. }
  49495. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49496. }
  49497. else
  49498. triggerParams = ActionManager[trigger.name];
  49499. for (var j = 0; j < trigger.children.length; j++) {
  49500. if (!trigger.detached)
  49501. traverse(trigger.children[j], triggerParams, null, null);
  49502. }
  49503. }
  49504. };
  49505. ActionManager.GetTriggerName = function (trigger) {
  49506. switch (trigger) {
  49507. case 0: return "NothingTrigger";
  49508. case 1: return "OnPickTrigger";
  49509. case 2: return "OnLeftPickTrigger";
  49510. case 3: return "OnRightPickTrigger";
  49511. case 4: return "OnCenterPickTrigger";
  49512. case 5: return "OnPickDownTrigger";
  49513. case 6: return "OnPickUpTrigger";
  49514. case 7: return "OnLongPressTrigger";
  49515. case 8: return "OnPointerOverTrigger";
  49516. case 9: return "OnPointerOutTrigger";
  49517. case 10: return "OnEveryFrameTrigger";
  49518. case 11: return "OnIntersectionEnterTrigger";
  49519. case 12: return "OnIntersectionExitTrigger";
  49520. case 13: return "OnKeyDownTrigger";
  49521. case 14: return "OnKeyUpTrigger";
  49522. case 15: return "OnPickOutTrigger";
  49523. default: return "";
  49524. }
  49525. };
  49526. // Statics
  49527. ActionManager._NothingTrigger = 0;
  49528. ActionManager._OnPickTrigger = 1;
  49529. ActionManager._OnLeftPickTrigger = 2;
  49530. ActionManager._OnRightPickTrigger = 3;
  49531. ActionManager._OnCenterPickTrigger = 4;
  49532. ActionManager._OnPickDownTrigger = 5;
  49533. ActionManager._OnDoublePickTrigger = 6;
  49534. ActionManager._OnPickUpTrigger = 7;
  49535. ActionManager._OnLongPressTrigger = 8;
  49536. ActionManager._OnPointerOverTrigger = 9;
  49537. ActionManager._OnPointerOutTrigger = 10;
  49538. ActionManager._OnEveryFrameTrigger = 11;
  49539. ActionManager._OnIntersectionEnterTrigger = 12;
  49540. ActionManager._OnIntersectionExitTrigger = 13;
  49541. ActionManager._OnKeyDownTrigger = 14;
  49542. ActionManager._OnKeyUpTrigger = 15;
  49543. ActionManager._OnPickOutTrigger = 16;
  49544. ActionManager.Triggers = {};
  49545. return ActionManager;
  49546. }());
  49547. BABYLON.ActionManager = ActionManager;
  49548. })(BABYLON || (BABYLON = {}));
  49549. //# sourceMappingURL=babylon.actionManager.js.map
  49550. "use strict";
  49551. var BABYLON;
  49552. (function (BABYLON) {
  49553. var InterpolateValueAction = /** @class */ (function (_super) {
  49554. __extends(InterpolateValueAction, _super);
  49555. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49556. if (duration === void 0) { duration = 1000; }
  49557. var _this = _super.call(this, triggerOptions, condition) || this;
  49558. _this.propertyPath = propertyPath;
  49559. _this.value = value;
  49560. _this.duration = duration;
  49561. _this.stopOtherAnimations = stopOtherAnimations;
  49562. _this.onInterpolationDone = onInterpolationDone;
  49563. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49564. _this._target = _this._effectiveTarget = target;
  49565. return _this;
  49566. }
  49567. InterpolateValueAction.prototype._prepare = function () {
  49568. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49569. this._property = this._getProperty(this.propertyPath);
  49570. };
  49571. InterpolateValueAction.prototype.execute = function () {
  49572. var _this = this;
  49573. var scene = this._actionManager.getScene();
  49574. var keys = [
  49575. {
  49576. frame: 0,
  49577. value: this._effectiveTarget[this._property]
  49578. }, {
  49579. frame: 100,
  49580. value: this.value
  49581. }
  49582. ];
  49583. var dataType;
  49584. if (typeof this.value === "number") {
  49585. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49586. }
  49587. else if (this.value instanceof BABYLON.Color3) {
  49588. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49589. }
  49590. else if (this.value instanceof BABYLON.Vector3) {
  49591. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49592. }
  49593. else if (this.value instanceof BABYLON.Matrix) {
  49594. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49595. }
  49596. else if (this.value instanceof BABYLON.Quaternion) {
  49597. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49598. }
  49599. else {
  49600. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49601. return;
  49602. }
  49603. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49604. animation.setKeys(keys);
  49605. if (this.stopOtherAnimations) {
  49606. scene.stopAnimation(this._effectiveTarget);
  49607. }
  49608. var wrapper = function () {
  49609. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49610. if (_this.onInterpolationDone) {
  49611. _this.onInterpolationDone();
  49612. }
  49613. };
  49614. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49615. };
  49616. InterpolateValueAction.prototype.serialize = function (parent) {
  49617. return _super.prototype._serialize.call(this, {
  49618. name: "InterpolateValueAction",
  49619. properties: [
  49620. BABYLON.Action._GetTargetProperty(this._target),
  49621. { name: "propertyPath", value: this.propertyPath },
  49622. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49623. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49624. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49625. ]
  49626. }, parent);
  49627. };
  49628. return InterpolateValueAction;
  49629. }(BABYLON.Action));
  49630. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49631. })(BABYLON || (BABYLON = {}));
  49632. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49633. "use strict";
  49634. var BABYLON;
  49635. (function (BABYLON) {
  49636. var SwitchBooleanAction = /** @class */ (function (_super) {
  49637. __extends(SwitchBooleanAction, _super);
  49638. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49639. var _this = _super.call(this, triggerOptions, condition) || this;
  49640. _this.propertyPath = propertyPath;
  49641. _this._target = _this._effectiveTarget = target;
  49642. return _this;
  49643. }
  49644. SwitchBooleanAction.prototype._prepare = function () {
  49645. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49646. this._property = this._getProperty(this.propertyPath);
  49647. };
  49648. SwitchBooleanAction.prototype.execute = function () {
  49649. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49650. };
  49651. SwitchBooleanAction.prototype.serialize = function (parent) {
  49652. return _super.prototype._serialize.call(this, {
  49653. name: "SwitchBooleanAction",
  49654. properties: [
  49655. BABYLON.Action._GetTargetProperty(this._target),
  49656. { name: "propertyPath", value: this.propertyPath }
  49657. ]
  49658. }, parent);
  49659. };
  49660. return SwitchBooleanAction;
  49661. }(BABYLON.Action));
  49662. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49663. var SetStateAction = /** @class */ (function (_super) {
  49664. __extends(SetStateAction, _super);
  49665. function SetStateAction(triggerOptions, target, value, condition) {
  49666. var _this = _super.call(this, triggerOptions, condition) || this;
  49667. _this.value = value;
  49668. _this._target = target;
  49669. return _this;
  49670. }
  49671. SetStateAction.prototype.execute = function () {
  49672. this._target.state = this.value;
  49673. };
  49674. SetStateAction.prototype.serialize = function (parent) {
  49675. return _super.prototype._serialize.call(this, {
  49676. name: "SetStateAction",
  49677. properties: [
  49678. BABYLON.Action._GetTargetProperty(this._target),
  49679. { name: "value", value: this.value }
  49680. ]
  49681. }, parent);
  49682. };
  49683. return SetStateAction;
  49684. }(BABYLON.Action));
  49685. BABYLON.SetStateAction = SetStateAction;
  49686. var SetValueAction = /** @class */ (function (_super) {
  49687. __extends(SetValueAction, _super);
  49688. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49689. var _this = _super.call(this, triggerOptions, condition) || this;
  49690. _this.propertyPath = propertyPath;
  49691. _this.value = value;
  49692. _this._target = _this._effectiveTarget = target;
  49693. return _this;
  49694. }
  49695. SetValueAction.prototype._prepare = function () {
  49696. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49697. this._property = this._getProperty(this.propertyPath);
  49698. };
  49699. SetValueAction.prototype.execute = function () {
  49700. this._effectiveTarget[this._property] = this.value;
  49701. if (this._target.markAsDirty) {
  49702. this._target.markAsDirty(this._property);
  49703. }
  49704. };
  49705. SetValueAction.prototype.serialize = function (parent) {
  49706. return _super.prototype._serialize.call(this, {
  49707. name: "SetValueAction",
  49708. properties: [
  49709. BABYLON.Action._GetTargetProperty(this._target),
  49710. { name: "propertyPath", value: this.propertyPath },
  49711. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49712. ]
  49713. }, parent);
  49714. };
  49715. return SetValueAction;
  49716. }(BABYLON.Action));
  49717. BABYLON.SetValueAction = SetValueAction;
  49718. var IncrementValueAction = /** @class */ (function (_super) {
  49719. __extends(IncrementValueAction, _super);
  49720. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49721. var _this = _super.call(this, triggerOptions, condition) || this;
  49722. _this.propertyPath = propertyPath;
  49723. _this.value = value;
  49724. _this._target = _this._effectiveTarget = target;
  49725. return _this;
  49726. }
  49727. IncrementValueAction.prototype._prepare = function () {
  49728. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49729. this._property = this._getProperty(this.propertyPath);
  49730. if (typeof this._effectiveTarget[this._property] !== "number") {
  49731. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49732. }
  49733. };
  49734. IncrementValueAction.prototype.execute = function () {
  49735. this._effectiveTarget[this._property] += this.value;
  49736. if (this._target.markAsDirty) {
  49737. this._target.markAsDirty(this._property);
  49738. }
  49739. };
  49740. IncrementValueAction.prototype.serialize = function (parent) {
  49741. return _super.prototype._serialize.call(this, {
  49742. name: "IncrementValueAction",
  49743. properties: [
  49744. BABYLON.Action._GetTargetProperty(this._target),
  49745. { name: "propertyPath", value: this.propertyPath },
  49746. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49747. ]
  49748. }, parent);
  49749. };
  49750. return IncrementValueAction;
  49751. }(BABYLON.Action));
  49752. BABYLON.IncrementValueAction = IncrementValueAction;
  49753. var PlayAnimationAction = /** @class */ (function (_super) {
  49754. __extends(PlayAnimationAction, _super);
  49755. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49756. var _this = _super.call(this, triggerOptions, condition) || this;
  49757. _this.from = from;
  49758. _this.to = to;
  49759. _this.loop = loop;
  49760. _this._target = target;
  49761. return _this;
  49762. }
  49763. PlayAnimationAction.prototype._prepare = function () {
  49764. };
  49765. PlayAnimationAction.prototype.execute = function () {
  49766. var scene = this._actionManager.getScene();
  49767. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49768. };
  49769. PlayAnimationAction.prototype.serialize = function (parent) {
  49770. return _super.prototype._serialize.call(this, {
  49771. name: "PlayAnimationAction",
  49772. properties: [
  49773. BABYLON.Action._GetTargetProperty(this._target),
  49774. { name: "from", value: String(this.from) },
  49775. { name: "to", value: String(this.to) },
  49776. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49777. ]
  49778. }, parent);
  49779. };
  49780. return PlayAnimationAction;
  49781. }(BABYLON.Action));
  49782. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49783. var StopAnimationAction = /** @class */ (function (_super) {
  49784. __extends(StopAnimationAction, _super);
  49785. function StopAnimationAction(triggerOptions, target, condition) {
  49786. var _this = _super.call(this, triggerOptions, condition) || this;
  49787. _this._target = target;
  49788. return _this;
  49789. }
  49790. StopAnimationAction.prototype._prepare = function () {
  49791. };
  49792. StopAnimationAction.prototype.execute = function () {
  49793. var scene = this._actionManager.getScene();
  49794. scene.stopAnimation(this._target);
  49795. };
  49796. StopAnimationAction.prototype.serialize = function (parent) {
  49797. return _super.prototype._serialize.call(this, {
  49798. name: "StopAnimationAction",
  49799. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49800. }, parent);
  49801. };
  49802. return StopAnimationAction;
  49803. }(BABYLON.Action));
  49804. BABYLON.StopAnimationAction = StopAnimationAction;
  49805. var DoNothingAction = /** @class */ (function (_super) {
  49806. __extends(DoNothingAction, _super);
  49807. function DoNothingAction(triggerOptions, condition) {
  49808. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49809. return _super.call(this, triggerOptions, condition) || this;
  49810. }
  49811. DoNothingAction.prototype.execute = function () {
  49812. };
  49813. DoNothingAction.prototype.serialize = function (parent) {
  49814. return _super.prototype._serialize.call(this, {
  49815. name: "DoNothingAction",
  49816. properties: []
  49817. }, parent);
  49818. };
  49819. return DoNothingAction;
  49820. }(BABYLON.Action));
  49821. BABYLON.DoNothingAction = DoNothingAction;
  49822. var CombineAction = /** @class */ (function (_super) {
  49823. __extends(CombineAction, _super);
  49824. function CombineAction(triggerOptions, children, condition) {
  49825. var _this = _super.call(this, triggerOptions, condition) || this;
  49826. _this.children = children;
  49827. return _this;
  49828. }
  49829. CombineAction.prototype._prepare = function () {
  49830. for (var index = 0; index < this.children.length; index++) {
  49831. this.children[index]._actionManager = this._actionManager;
  49832. this.children[index]._prepare();
  49833. }
  49834. };
  49835. CombineAction.prototype.execute = function (evt) {
  49836. for (var index = 0; index < this.children.length; index++) {
  49837. this.children[index].execute(evt);
  49838. }
  49839. };
  49840. CombineAction.prototype.serialize = function (parent) {
  49841. var serializationObject = _super.prototype._serialize.call(this, {
  49842. name: "CombineAction",
  49843. properties: [],
  49844. combine: []
  49845. }, parent);
  49846. for (var i = 0; i < this.children.length; i++) {
  49847. serializationObject.combine.push(this.children[i].serialize(null));
  49848. }
  49849. return serializationObject;
  49850. };
  49851. return CombineAction;
  49852. }(BABYLON.Action));
  49853. BABYLON.CombineAction = CombineAction;
  49854. var ExecuteCodeAction = /** @class */ (function (_super) {
  49855. __extends(ExecuteCodeAction, _super);
  49856. function ExecuteCodeAction(triggerOptions, func, condition) {
  49857. var _this = _super.call(this, triggerOptions, condition) || this;
  49858. _this.func = func;
  49859. return _this;
  49860. }
  49861. ExecuteCodeAction.prototype.execute = function (evt) {
  49862. this.func(evt);
  49863. };
  49864. return ExecuteCodeAction;
  49865. }(BABYLON.Action));
  49866. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49867. var SetParentAction = /** @class */ (function (_super) {
  49868. __extends(SetParentAction, _super);
  49869. function SetParentAction(triggerOptions, target, parent, condition) {
  49870. var _this = _super.call(this, triggerOptions, condition) || this;
  49871. _this._target = target;
  49872. _this._parent = parent;
  49873. return _this;
  49874. }
  49875. SetParentAction.prototype._prepare = function () {
  49876. };
  49877. SetParentAction.prototype.execute = function () {
  49878. if (this._target.parent === this._parent) {
  49879. return;
  49880. }
  49881. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49882. invertParentWorldMatrix.invert();
  49883. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49884. this._target.parent = this._parent;
  49885. };
  49886. SetParentAction.prototype.serialize = function (parent) {
  49887. return _super.prototype._serialize.call(this, {
  49888. name: "SetParentAction",
  49889. properties: [
  49890. BABYLON.Action._GetTargetProperty(this._target),
  49891. BABYLON.Action._GetTargetProperty(this._parent),
  49892. ]
  49893. }, parent);
  49894. };
  49895. return SetParentAction;
  49896. }(BABYLON.Action));
  49897. BABYLON.SetParentAction = SetParentAction;
  49898. var PlaySoundAction = /** @class */ (function (_super) {
  49899. __extends(PlaySoundAction, _super);
  49900. function PlaySoundAction(triggerOptions, sound, condition) {
  49901. var _this = _super.call(this, triggerOptions, condition) || this;
  49902. _this._sound = sound;
  49903. return _this;
  49904. }
  49905. PlaySoundAction.prototype._prepare = function () {
  49906. };
  49907. PlaySoundAction.prototype.execute = function () {
  49908. if (this._sound !== undefined)
  49909. this._sound.play();
  49910. };
  49911. PlaySoundAction.prototype.serialize = function (parent) {
  49912. return _super.prototype._serialize.call(this, {
  49913. name: "PlaySoundAction",
  49914. properties: [{ name: "sound", value: this._sound.name }]
  49915. }, parent);
  49916. };
  49917. return PlaySoundAction;
  49918. }(BABYLON.Action));
  49919. BABYLON.PlaySoundAction = PlaySoundAction;
  49920. var StopSoundAction = /** @class */ (function (_super) {
  49921. __extends(StopSoundAction, _super);
  49922. function StopSoundAction(triggerOptions, sound, condition) {
  49923. var _this = _super.call(this, triggerOptions, condition) || this;
  49924. _this._sound = sound;
  49925. return _this;
  49926. }
  49927. StopSoundAction.prototype._prepare = function () {
  49928. };
  49929. StopSoundAction.prototype.execute = function () {
  49930. if (this._sound !== undefined)
  49931. this._sound.stop();
  49932. };
  49933. StopSoundAction.prototype.serialize = function (parent) {
  49934. return _super.prototype._serialize.call(this, {
  49935. name: "StopSoundAction",
  49936. properties: [{ name: "sound", value: this._sound.name }]
  49937. }, parent);
  49938. };
  49939. return StopSoundAction;
  49940. }(BABYLON.Action));
  49941. BABYLON.StopSoundAction = StopSoundAction;
  49942. })(BABYLON || (BABYLON = {}));
  49943. //# sourceMappingURL=babylon.directActions.js.map
  49944. "use strict";
  49945. var BABYLON;
  49946. (function (BABYLON) {
  49947. var SpriteManager = /** @class */ (function () {
  49948. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49949. if (epsilon === void 0) { epsilon = 0.01; }
  49950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49951. this.name = name;
  49952. this.sprites = new Array();
  49953. this.renderingGroupId = 0;
  49954. this.layerMask = 0x0FFFFFFF;
  49955. this.fogEnabled = true;
  49956. this.isPickable = false;
  49957. /**
  49958. * An event triggered when the manager is disposed.
  49959. * @type {BABYLON.Observable}
  49960. */
  49961. this.onDisposeObservable = new BABYLON.Observable();
  49962. this._vertexBuffers = {};
  49963. this._capacity = capacity;
  49964. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49965. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49966. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49967. if (cellSize.width && cellSize.height) {
  49968. this.cellWidth = cellSize.width;
  49969. this.cellHeight = cellSize.height;
  49970. }
  49971. else if (cellSize !== undefined) {
  49972. this.cellWidth = cellSize;
  49973. this.cellHeight = cellSize;
  49974. }
  49975. else {
  49976. return;
  49977. }
  49978. this._epsilon = epsilon;
  49979. this._scene = scene;
  49980. this._scene.spriteManagers.push(this);
  49981. var indices = [];
  49982. var index = 0;
  49983. for (var count = 0; count < capacity; count++) {
  49984. indices.push(index);
  49985. indices.push(index + 1);
  49986. indices.push(index + 2);
  49987. indices.push(index);
  49988. indices.push(index + 2);
  49989. indices.push(index + 3);
  49990. index += 4;
  49991. }
  49992. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49993. // VBO
  49994. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49995. this._vertexData = new Float32Array(capacity * 16 * 4);
  49996. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49997. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49998. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49999. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50000. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50001. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50002. this._vertexBuffers["options"] = options;
  50003. this._vertexBuffers["cellInfo"] = cellInfo;
  50004. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50005. // Effects
  50006. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50007. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50008. }
  50009. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50010. set: function (callback) {
  50011. if (this._onDisposeObserver) {
  50012. this.onDisposeObservable.remove(this._onDisposeObserver);
  50013. }
  50014. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50015. },
  50016. enumerable: true,
  50017. configurable: true
  50018. });
  50019. Object.defineProperty(SpriteManager.prototype, "texture", {
  50020. get: function () {
  50021. return this._spriteTexture;
  50022. },
  50023. set: function (value) {
  50024. this._spriteTexture = value;
  50025. },
  50026. enumerable: true,
  50027. configurable: true
  50028. });
  50029. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50030. var arrayOffset = index * 16;
  50031. if (offsetX === 0)
  50032. offsetX = this._epsilon;
  50033. else if (offsetX === 1)
  50034. offsetX = 1 - this._epsilon;
  50035. if (offsetY === 0)
  50036. offsetY = this._epsilon;
  50037. else if (offsetY === 1)
  50038. offsetY = 1 - this._epsilon;
  50039. this._vertexData[arrayOffset] = sprite.position.x;
  50040. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50041. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50042. this._vertexData[arrayOffset + 3] = sprite.angle;
  50043. this._vertexData[arrayOffset + 4] = sprite.width;
  50044. this._vertexData[arrayOffset + 5] = sprite.height;
  50045. this._vertexData[arrayOffset + 6] = offsetX;
  50046. this._vertexData[arrayOffset + 7] = offsetY;
  50047. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50048. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50049. var offset = (sprite.cellIndex / rowSize) >> 0;
  50050. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50051. this._vertexData[arrayOffset + 11] = offset;
  50052. // Color
  50053. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50054. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50055. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50056. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50057. };
  50058. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50059. var count = Math.min(this._capacity, this.sprites.length);
  50060. var min = BABYLON.Vector3.Zero();
  50061. var max = BABYLON.Vector3.Zero();
  50062. var distance = Number.MAX_VALUE;
  50063. var currentSprite = null;
  50064. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50065. var cameraView = camera.getViewMatrix();
  50066. for (var index = 0; index < count; index++) {
  50067. var sprite = this.sprites[index];
  50068. if (!sprite) {
  50069. continue;
  50070. }
  50071. if (predicate) {
  50072. if (!predicate(sprite)) {
  50073. continue;
  50074. }
  50075. }
  50076. else if (!sprite.isPickable) {
  50077. continue;
  50078. }
  50079. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50080. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50081. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50082. if (ray.intersectsBoxMinMax(min, max)) {
  50083. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50084. if (distance > currentDistance) {
  50085. distance = currentDistance;
  50086. currentSprite = sprite;
  50087. if (fastCheck) {
  50088. break;
  50089. }
  50090. }
  50091. }
  50092. }
  50093. if (currentSprite) {
  50094. var result = new BABYLON.PickingInfo();
  50095. result.hit = true;
  50096. result.pickedSprite = currentSprite;
  50097. result.distance = distance;
  50098. return result;
  50099. }
  50100. return null;
  50101. };
  50102. SpriteManager.prototype.render = function () {
  50103. // Check
  50104. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50105. return;
  50106. var engine = this._scene.getEngine();
  50107. var baseSize = this._spriteTexture.getBaseSize();
  50108. // Sprites
  50109. var deltaTime = engine.getDeltaTime();
  50110. var max = Math.min(this._capacity, this.sprites.length);
  50111. var rowSize = baseSize.width / this.cellWidth;
  50112. var offset = 0;
  50113. for (var index = 0; index < max; index++) {
  50114. var sprite = this.sprites[index];
  50115. if (!sprite) {
  50116. continue;
  50117. }
  50118. sprite._animate(deltaTime);
  50119. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50120. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50121. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50122. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50123. }
  50124. this._buffer.update(this._vertexData);
  50125. // Render
  50126. var effect = this._effectBase;
  50127. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50128. effect = this._effectFog;
  50129. }
  50130. engine.enableEffect(effect);
  50131. var viewMatrix = this._scene.getViewMatrix();
  50132. effect.setTexture("diffuseSampler", this._spriteTexture);
  50133. effect.setMatrix("view", viewMatrix);
  50134. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50135. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50136. // Fog
  50137. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50138. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50139. effect.setColor3("vFogColor", this._scene.fogColor);
  50140. }
  50141. // VBOs
  50142. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50143. // Draw order
  50144. engine.setDepthFunctionToLessOrEqual();
  50145. effect.setBool("alphaTest", true);
  50146. engine.setColorWrite(false);
  50147. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50148. engine.setColorWrite(true);
  50149. effect.setBool("alphaTest", false);
  50150. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50151. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50152. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50153. };
  50154. SpriteManager.prototype.dispose = function () {
  50155. if (this._buffer) {
  50156. this._buffer.dispose();
  50157. this._buffer = null;
  50158. }
  50159. if (this._indexBuffer) {
  50160. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50161. this._indexBuffer = null;
  50162. }
  50163. if (this._spriteTexture) {
  50164. this._spriteTexture.dispose();
  50165. this._spriteTexture = null;
  50166. }
  50167. // Remove from scene
  50168. var index = this._scene.spriteManagers.indexOf(this);
  50169. this._scene.spriteManagers.splice(index, 1);
  50170. // Callback
  50171. this.onDisposeObservable.notifyObservers(this);
  50172. this.onDisposeObservable.clear();
  50173. };
  50174. return SpriteManager;
  50175. }());
  50176. BABYLON.SpriteManager = SpriteManager;
  50177. })(BABYLON || (BABYLON = {}));
  50178. //# sourceMappingURL=babylon.spriteManager.js.map
  50179. "use strict";
  50180. var BABYLON;
  50181. (function (BABYLON) {
  50182. var Sprite = /** @class */ (function () {
  50183. function Sprite(name, manager) {
  50184. this.name = name;
  50185. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50186. this.width = 1.0;
  50187. this.height = 1.0;
  50188. this.angle = 0;
  50189. this.cellIndex = 0;
  50190. this.invertU = 0;
  50191. this.invertV = 0;
  50192. this.animations = new Array();
  50193. this.isPickable = false;
  50194. this._animationStarted = false;
  50195. this._loopAnimation = false;
  50196. this._fromIndex = 0;
  50197. this._toIndex = 0;
  50198. this._delay = 0;
  50199. this._direction = 1;
  50200. this._time = 0;
  50201. this._manager = manager;
  50202. this._manager.sprites.push(this);
  50203. this.position = BABYLON.Vector3.Zero();
  50204. }
  50205. Object.defineProperty(Sprite.prototype, "size", {
  50206. get: function () {
  50207. return this.width;
  50208. },
  50209. set: function (value) {
  50210. this.width = value;
  50211. this.height = value;
  50212. },
  50213. enumerable: true,
  50214. configurable: true
  50215. });
  50216. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50217. this._fromIndex = from;
  50218. this._toIndex = to;
  50219. this._loopAnimation = loop;
  50220. this._delay = delay;
  50221. this._animationStarted = true;
  50222. this._direction = from < to ? 1 : -1;
  50223. this.cellIndex = from;
  50224. this._time = 0;
  50225. this._onAnimationEnd = onAnimationEnd;
  50226. };
  50227. Sprite.prototype.stopAnimation = function () {
  50228. this._animationStarted = false;
  50229. };
  50230. Sprite.prototype._animate = function (deltaTime) {
  50231. if (!this._animationStarted)
  50232. return;
  50233. this._time += deltaTime;
  50234. if (this._time > this._delay) {
  50235. this._time = this._time % this._delay;
  50236. this.cellIndex += this._direction;
  50237. if (this.cellIndex > this._toIndex) {
  50238. if (this._loopAnimation) {
  50239. this.cellIndex = this._fromIndex;
  50240. }
  50241. else {
  50242. this.cellIndex = this._toIndex;
  50243. this._animationStarted = false;
  50244. if (this._onAnimationEnd) {
  50245. this._onAnimationEnd();
  50246. }
  50247. if (this.disposeWhenFinishedAnimating) {
  50248. this.dispose();
  50249. }
  50250. }
  50251. }
  50252. }
  50253. };
  50254. Sprite.prototype.dispose = function () {
  50255. for (var i = 0; i < this._manager.sprites.length; i++) {
  50256. if (this._manager.sprites[i] == this) {
  50257. this._manager.sprites.splice(i, 1);
  50258. }
  50259. }
  50260. };
  50261. return Sprite;
  50262. }());
  50263. BABYLON.Sprite = Sprite;
  50264. })(BABYLON || (BABYLON = {}));
  50265. //# sourceMappingURL=babylon.sprite.js.map
  50266. "use strict";
  50267. var BABYLON;
  50268. (function (BABYLON) {
  50269. var IntersectionInfo = /** @class */ (function () {
  50270. function IntersectionInfo(bu, bv, distance) {
  50271. this.bu = bu;
  50272. this.bv = bv;
  50273. this.distance = distance;
  50274. this.faceId = 0;
  50275. this.subMeshId = 0;
  50276. }
  50277. return IntersectionInfo;
  50278. }());
  50279. BABYLON.IntersectionInfo = IntersectionInfo;
  50280. var PickingInfo = /** @class */ (function () {
  50281. function PickingInfo() {
  50282. this.hit = false;
  50283. this.distance = 0;
  50284. this.pickedPoint = null;
  50285. this.pickedMesh = null;
  50286. this.bu = 0;
  50287. this.bv = 0;
  50288. this.faceId = -1;
  50289. this.subMeshId = 0;
  50290. this.pickedSprite = null;
  50291. }
  50292. // Methods
  50293. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50294. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50295. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50296. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50297. return null;
  50298. }
  50299. var indices = this.pickedMesh.getIndices();
  50300. if (!indices) {
  50301. return null;
  50302. }
  50303. var result;
  50304. if (useVerticesNormals) {
  50305. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50306. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50307. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50308. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50309. normal0 = normal0.scale(this.bu);
  50310. normal1 = normal1.scale(this.bv);
  50311. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50312. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50313. }
  50314. else {
  50315. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50316. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50317. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50318. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50319. var p1p2 = vertex1.subtract(vertex2);
  50320. var p3p2 = vertex3.subtract(vertex2);
  50321. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50322. }
  50323. if (useWorldCoordinates) {
  50324. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50325. }
  50326. return BABYLON.Vector3.Normalize(result);
  50327. };
  50328. PickingInfo.prototype.getTextureCoordinates = function () {
  50329. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50330. return null;
  50331. }
  50332. var indices = this.pickedMesh.getIndices();
  50333. if (!indices) {
  50334. return null;
  50335. }
  50336. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50337. if (!uvs) {
  50338. return null;
  50339. }
  50340. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50341. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50342. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50343. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50344. uv1 = uv1.scale(this.bu);
  50345. uv2 = uv2.scale(this.bv);
  50346. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50347. };
  50348. return PickingInfo;
  50349. }());
  50350. BABYLON.PickingInfo = PickingInfo;
  50351. })(BABYLON || (BABYLON = {}));
  50352. //# sourceMappingURL=babylon.pickingInfo.js.map
  50353. "use strict";
  50354. var BABYLON;
  50355. (function (BABYLON) {
  50356. var Ray = /** @class */ (function () {
  50357. function Ray(origin, direction, length) {
  50358. if (length === void 0) { length = Number.MAX_VALUE; }
  50359. this.origin = origin;
  50360. this.direction = direction;
  50361. this.length = length;
  50362. }
  50363. // Methods
  50364. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50365. var d = 0.0;
  50366. var maxValue = Number.MAX_VALUE;
  50367. var inv;
  50368. var min;
  50369. var max;
  50370. var temp;
  50371. if (Math.abs(this.direction.x) < 0.0000001) {
  50372. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50373. return false;
  50374. }
  50375. }
  50376. else {
  50377. inv = 1.0 / this.direction.x;
  50378. min = (minimum.x - this.origin.x) * inv;
  50379. max = (maximum.x - this.origin.x) * inv;
  50380. if (max === -Infinity) {
  50381. max = Infinity;
  50382. }
  50383. if (min > max) {
  50384. temp = min;
  50385. min = max;
  50386. max = temp;
  50387. }
  50388. d = Math.max(min, d);
  50389. maxValue = Math.min(max, maxValue);
  50390. if (d > maxValue) {
  50391. return false;
  50392. }
  50393. }
  50394. if (Math.abs(this.direction.y) < 0.0000001) {
  50395. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50396. return false;
  50397. }
  50398. }
  50399. else {
  50400. inv = 1.0 / this.direction.y;
  50401. min = (minimum.y - this.origin.y) * inv;
  50402. max = (maximum.y - this.origin.y) * inv;
  50403. if (max === -Infinity) {
  50404. max = Infinity;
  50405. }
  50406. if (min > max) {
  50407. temp = min;
  50408. min = max;
  50409. max = temp;
  50410. }
  50411. d = Math.max(min, d);
  50412. maxValue = Math.min(max, maxValue);
  50413. if (d > maxValue) {
  50414. return false;
  50415. }
  50416. }
  50417. if (Math.abs(this.direction.z) < 0.0000001) {
  50418. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50419. return false;
  50420. }
  50421. }
  50422. else {
  50423. inv = 1.0 / this.direction.z;
  50424. min = (minimum.z - this.origin.z) * inv;
  50425. max = (maximum.z - this.origin.z) * inv;
  50426. if (max === -Infinity) {
  50427. max = Infinity;
  50428. }
  50429. if (min > max) {
  50430. temp = min;
  50431. min = max;
  50432. max = temp;
  50433. }
  50434. d = Math.max(min, d);
  50435. maxValue = Math.min(max, maxValue);
  50436. if (d > maxValue) {
  50437. return false;
  50438. }
  50439. }
  50440. return true;
  50441. };
  50442. Ray.prototype.intersectsBox = function (box) {
  50443. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50444. };
  50445. Ray.prototype.intersectsSphere = function (sphere) {
  50446. var x = sphere.center.x - this.origin.x;
  50447. var y = sphere.center.y - this.origin.y;
  50448. var z = sphere.center.z - this.origin.z;
  50449. var pyth = (x * x) + (y * y) + (z * z);
  50450. var rr = sphere.radius * sphere.radius;
  50451. if (pyth <= rr) {
  50452. return true;
  50453. }
  50454. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50455. if (dot < 0.0) {
  50456. return false;
  50457. }
  50458. var temp = pyth - (dot * dot);
  50459. return temp <= rr;
  50460. };
  50461. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50462. if (!this._edge1) {
  50463. this._edge1 = BABYLON.Vector3.Zero();
  50464. this._edge2 = BABYLON.Vector3.Zero();
  50465. this._pvec = BABYLON.Vector3.Zero();
  50466. this._tvec = BABYLON.Vector3.Zero();
  50467. this._qvec = BABYLON.Vector3.Zero();
  50468. }
  50469. vertex1.subtractToRef(vertex0, this._edge1);
  50470. vertex2.subtractToRef(vertex0, this._edge2);
  50471. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50472. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50473. if (det === 0) {
  50474. return null;
  50475. }
  50476. var invdet = 1 / det;
  50477. this.origin.subtractToRef(vertex0, this._tvec);
  50478. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50479. if (bu < 0 || bu > 1.0) {
  50480. return null;
  50481. }
  50482. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50483. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50484. if (bv < 0 || bu + bv > 1.0) {
  50485. return null;
  50486. }
  50487. //check if the distance is longer than the predefined length.
  50488. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50489. if (distance > this.length) {
  50490. return null;
  50491. }
  50492. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50493. };
  50494. Ray.prototype.intersectsPlane = function (plane) {
  50495. var distance;
  50496. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50497. if (Math.abs(result1) < 9.99999997475243E-07) {
  50498. return null;
  50499. }
  50500. else {
  50501. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50502. distance = (-plane.d - result2) / result1;
  50503. if (distance < 0.0) {
  50504. if (distance < -9.99999997475243E-07) {
  50505. return null;
  50506. }
  50507. else {
  50508. return 0;
  50509. }
  50510. }
  50511. return distance;
  50512. }
  50513. };
  50514. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50515. var tm = BABYLON.Tmp.Matrix[0];
  50516. mesh.getWorldMatrix().invertToRef(tm);
  50517. if (this._tmpRay) {
  50518. Ray.TransformToRef(this, tm, this._tmpRay);
  50519. }
  50520. else {
  50521. this._tmpRay = Ray.Transform(this, tm);
  50522. }
  50523. return mesh.intersects(this._tmpRay, fastCheck);
  50524. };
  50525. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50526. if (results) {
  50527. results.length = 0;
  50528. }
  50529. else {
  50530. results = [];
  50531. }
  50532. for (var i = 0; i < meshes.length; i++) {
  50533. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50534. if (pickInfo.hit) {
  50535. results.push(pickInfo);
  50536. }
  50537. }
  50538. results.sort(this._comparePickingInfo);
  50539. return results;
  50540. };
  50541. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50542. if (pickingInfoA.distance < pickingInfoB.distance) {
  50543. return -1;
  50544. }
  50545. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50546. return 1;
  50547. }
  50548. else {
  50549. return 0;
  50550. }
  50551. };
  50552. /**
  50553. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50554. * @param sega the first point of the segment to test the intersection against
  50555. * @param segb the second point of the segment to test the intersection against
  50556. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50557. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50558. */
  50559. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50560. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50561. var u = segb.subtract(sega);
  50562. var v = rsegb.subtract(this.origin);
  50563. var w = sega.subtract(this.origin);
  50564. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50565. var b = BABYLON.Vector3.Dot(u, v);
  50566. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50567. var d = BABYLON.Vector3.Dot(u, w);
  50568. var e = BABYLON.Vector3.Dot(v, w);
  50569. var D = a * c - b * b; // always >= 0
  50570. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50571. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50572. // compute the line parameters of the two closest points
  50573. if (D < Ray.smallnum) {
  50574. sN = 0.0; // force using point P0 on segment S1
  50575. sD = 1.0; // to prevent possible division by 0.0 later
  50576. tN = e;
  50577. tD = c;
  50578. }
  50579. else {
  50580. sN = (b * e - c * d);
  50581. tN = (a * e - b * d);
  50582. if (sN < 0.0) {
  50583. sN = 0.0;
  50584. tN = e;
  50585. tD = c;
  50586. }
  50587. else if (sN > sD) {
  50588. sN = sD;
  50589. tN = e + b;
  50590. tD = c;
  50591. }
  50592. }
  50593. if (tN < 0.0) {
  50594. tN = 0.0;
  50595. // recompute sc for this edge
  50596. if (-d < 0.0) {
  50597. sN = 0.0;
  50598. }
  50599. else if (-d > a)
  50600. sN = sD;
  50601. else {
  50602. sN = -d;
  50603. sD = a;
  50604. }
  50605. }
  50606. else if (tN > tD) {
  50607. tN = tD;
  50608. // recompute sc for this edge
  50609. if ((-d + b) < 0.0) {
  50610. sN = 0;
  50611. }
  50612. else if ((-d + b) > a) {
  50613. sN = sD;
  50614. }
  50615. else {
  50616. sN = (-d + b);
  50617. sD = a;
  50618. }
  50619. }
  50620. // finally do the division to get sc and tc
  50621. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50622. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50623. // get the difference of the two closest points
  50624. var qtc = v.multiplyByFloats(tc, tc, tc);
  50625. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50626. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50627. if (isIntersected) {
  50628. return qtc.length();
  50629. }
  50630. return -1;
  50631. };
  50632. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50633. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50634. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50635. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50636. this.direction.normalize();
  50637. return this;
  50638. };
  50639. // Statics
  50640. Ray.Zero = function () {
  50641. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50642. };
  50643. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50644. var result = Ray.Zero();
  50645. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50646. };
  50647. /**
  50648. * 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
  50649. * transformed to the given world matrix.
  50650. * @param origin The origin point
  50651. * @param end The end point
  50652. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50653. */
  50654. Ray.CreateNewFromTo = function (origin, end, world) {
  50655. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50656. var direction = end.subtract(origin);
  50657. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50658. direction.normalize();
  50659. return Ray.Transform(new Ray(origin, direction, length), world);
  50660. };
  50661. Ray.Transform = function (ray, matrix) {
  50662. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50663. Ray.TransformToRef(ray, matrix, result);
  50664. return result;
  50665. };
  50666. Ray.TransformToRef = function (ray, matrix, result) {
  50667. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50668. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50669. result.length = ray.length;
  50670. var dir = result.direction;
  50671. var len = dir.length();
  50672. if (!(len === 0 || len === 1)) {
  50673. var num = 1.0 / len;
  50674. dir.x *= num;
  50675. dir.y *= num;
  50676. dir.z *= num;
  50677. result.length *= len;
  50678. }
  50679. };
  50680. Ray.smallnum = 0.00000001;
  50681. Ray.rayl = 10e8;
  50682. return Ray;
  50683. }());
  50684. BABYLON.Ray = Ray;
  50685. })(BABYLON || (BABYLON = {}));
  50686. //# sourceMappingURL=babylon.ray.js.map
  50687. "use strict";
  50688. var BABYLON;
  50689. (function (BABYLON) {
  50690. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50691. if (boxMin.x > sphereCenter.x + sphereRadius)
  50692. return false;
  50693. if (sphereCenter.x - sphereRadius > boxMax.x)
  50694. return false;
  50695. if (boxMin.y > sphereCenter.y + sphereRadius)
  50696. return false;
  50697. if (sphereCenter.y - sphereRadius > boxMax.y)
  50698. return false;
  50699. if (boxMin.z > sphereCenter.z + sphereRadius)
  50700. return false;
  50701. if (sphereCenter.z - sphereRadius > boxMax.z)
  50702. return false;
  50703. return true;
  50704. };
  50705. var getLowestRoot = (function () {
  50706. var result = { root: 0, found: false };
  50707. return function (a, b, c, maxR) {
  50708. result.root = 0;
  50709. result.found = false;
  50710. var determinant = b * b - 4.0 * a * c;
  50711. if (determinant < 0)
  50712. return result;
  50713. var sqrtD = Math.sqrt(determinant);
  50714. var r1 = (-b - sqrtD) / (2.0 * a);
  50715. var r2 = (-b + sqrtD) / (2.0 * a);
  50716. if (r1 > r2) {
  50717. var temp = r2;
  50718. r2 = r1;
  50719. r1 = temp;
  50720. }
  50721. if (r1 > 0 && r1 < maxR) {
  50722. result.root = r1;
  50723. result.found = true;
  50724. return result;
  50725. }
  50726. if (r2 > 0 && r2 < maxR) {
  50727. result.root = r2;
  50728. result.found = true;
  50729. return result;
  50730. }
  50731. return result;
  50732. };
  50733. })();
  50734. var Collider = /** @class */ (function () {
  50735. function Collider() {
  50736. this._collisionPoint = BABYLON.Vector3.Zero();
  50737. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50738. this._tempVector = BABYLON.Vector3.Zero();
  50739. this._tempVector2 = BABYLON.Vector3.Zero();
  50740. this._tempVector3 = BABYLON.Vector3.Zero();
  50741. this._tempVector4 = BABYLON.Vector3.Zero();
  50742. this._edge = BABYLON.Vector3.Zero();
  50743. this._baseToVertex = BABYLON.Vector3.Zero();
  50744. this._destinationPoint = BABYLON.Vector3.Zero();
  50745. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50746. this._displacementVector = BABYLON.Vector3.Zero();
  50747. this._radius = BABYLON.Vector3.One();
  50748. this._retry = 0;
  50749. this._basePointWorld = BABYLON.Vector3.Zero();
  50750. this._velocityWorld = BABYLON.Vector3.Zero();
  50751. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50752. this._collisionMask = -1;
  50753. }
  50754. Object.defineProperty(Collider.prototype, "collisionMask", {
  50755. get: function () {
  50756. return this._collisionMask;
  50757. },
  50758. set: function (mask) {
  50759. this._collisionMask = !isNaN(mask) ? mask : -1;
  50760. },
  50761. enumerable: true,
  50762. configurable: true
  50763. });
  50764. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50765. /**
  50766. * Gets the plane normal used to compute the sliding response (in local space)
  50767. */
  50768. get: function () {
  50769. return this._slidePlaneNormal;
  50770. },
  50771. enumerable: true,
  50772. configurable: true
  50773. });
  50774. // Methods
  50775. Collider.prototype._initialize = function (source, dir, e) {
  50776. this._velocity = dir;
  50777. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50778. this._basePoint = source;
  50779. source.multiplyToRef(this._radius, this._basePointWorld);
  50780. dir.multiplyToRef(this._radius, this._velocityWorld);
  50781. this._velocityWorldLength = this._velocityWorld.length();
  50782. this._epsilon = e;
  50783. this.collisionFound = false;
  50784. };
  50785. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50786. pa.subtractToRef(point, this._tempVector);
  50787. pb.subtractToRef(point, this._tempVector2);
  50788. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50789. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50790. if (d < 0)
  50791. return false;
  50792. pc.subtractToRef(point, this._tempVector3);
  50793. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50794. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50795. if (d < 0)
  50796. return false;
  50797. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50798. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50799. return d >= 0;
  50800. };
  50801. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50802. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50803. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50804. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50805. return false;
  50806. }
  50807. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50808. return false;
  50809. return true;
  50810. };
  50811. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50812. var t0;
  50813. var embeddedInPlane = false;
  50814. //defensive programming, actually not needed.
  50815. if (!trianglePlaneArray) {
  50816. trianglePlaneArray = [];
  50817. }
  50818. if (!trianglePlaneArray[faceIndex]) {
  50819. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50820. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50821. }
  50822. var trianglePlane = trianglePlaneArray[faceIndex];
  50823. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50824. return;
  50825. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50826. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50827. if (normalDotVelocity == 0) {
  50828. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50829. return;
  50830. embeddedInPlane = true;
  50831. t0 = 0;
  50832. }
  50833. else {
  50834. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50835. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50836. if (t0 > t1) {
  50837. var temp = t1;
  50838. t1 = t0;
  50839. t0 = temp;
  50840. }
  50841. if (t0 > 1.0 || t1 < 0.0)
  50842. return;
  50843. if (t0 < 0)
  50844. t0 = 0;
  50845. if (t0 > 1.0)
  50846. t0 = 1.0;
  50847. }
  50848. this._collisionPoint.copyFromFloats(0, 0, 0);
  50849. var found = false;
  50850. var t = 1.0;
  50851. if (!embeddedInPlane) {
  50852. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50853. this._velocity.scaleToRef(t0, this._tempVector);
  50854. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50855. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50856. found = true;
  50857. t = t0;
  50858. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50859. }
  50860. }
  50861. if (!found) {
  50862. var velocitySquaredLength = this._velocity.lengthSquared();
  50863. var a = velocitySquaredLength;
  50864. this._basePoint.subtractToRef(p1, this._tempVector);
  50865. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50866. var c = this._tempVector.lengthSquared() - 1.0;
  50867. var lowestRoot = getLowestRoot(a, b, c, t);
  50868. if (lowestRoot.found) {
  50869. t = lowestRoot.root;
  50870. found = true;
  50871. this._collisionPoint.copyFrom(p1);
  50872. }
  50873. this._basePoint.subtractToRef(p2, this._tempVector);
  50874. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50875. c = this._tempVector.lengthSquared() - 1.0;
  50876. lowestRoot = getLowestRoot(a, b, c, t);
  50877. if (lowestRoot.found) {
  50878. t = lowestRoot.root;
  50879. found = true;
  50880. this._collisionPoint.copyFrom(p2);
  50881. }
  50882. this._basePoint.subtractToRef(p3, this._tempVector);
  50883. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50884. c = this._tempVector.lengthSquared() - 1.0;
  50885. lowestRoot = getLowestRoot(a, b, c, t);
  50886. if (lowestRoot.found) {
  50887. t = lowestRoot.root;
  50888. found = true;
  50889. this._collisionPoint.copyFrom(p3);
  50890. }
  50891. p2.subtractToRef(p1, this._edge);
  50892. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50893. var edgeSquaredLength = this._edge.lengthSquared();
  50894. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50895. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50896. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50897. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50898. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50899. lowestRoot = getLowestRoot(a, b, c, t);
  50900. if (lowestRoot.found) {
  50901. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50902. if (f >= 0.0 && f <= 1.0) {
  50903. t = lowestRoot.root;
  50904. found = true;
  50905. this._edge.scaleInPlace(f);
  50906. p1.addToRef(this._edge, this._collisionPoint);
  50907. }
  50908. }
  50909. p3.subtractToRef(p2, this._edge);
  50910. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50911. edgeSquaredLength = this._edge.lengthSquared();
  50912. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50913. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50914. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50915. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50916. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50917. lowestRoot = getLowestRoot(a, b, c, t);
  50918. if (lowestRoot.found) {
  50919. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50920. if (f >= 0.0 && f <= 1.0) {
  50921. t = lowestRoot.root;
  50922. found = true;
  50923. this._edge.scaleInPlace(f);
  50924. p2.addToRef(this._edge, this._collisionPoint);
  50925. }
  50926. }
  50927. p1.subtractToRef(p3, this._edge);
  50928. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50929. edgeSquaredLength = this._edge.lengthSquared();
  50930. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50931. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50932. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50933. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50934. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50935. lowestRoot = getLowestRoot(a, b, c, t);
  50936. if (lowestRoot.found) {
  50937. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50938. if (f >= 0.0 && f <= 1.0) {
  50939. t = lowestRoot.root;
  50940. found = true;
  50941. this._edge.scaleInPlace(f);
  50942. p3.addToRef(this._edge, this._collisionPoint);
  50943. }
  50944. }
  50945. }
  50946. if (found) {
  50947. var distToCollision = t * this._velocity.length();
  50948. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50949. if (!this.intersectionPoint) {
  50950. this.intersectionPoint = this._collisionPoint.clone();
  50951. }
  50952. else {
  50953. this.intersectionPoint.copyFrom(this._collisionPoint);
  50954. }
  50955. this._nearestDistance = distToCollision;
  50956. this.collisionFound = true;
  50957. }
  50958. }
  50959. };
  50960. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50961. for (var i = indexStart; i < indexEnd; i += 3) {
  50962. var p1 = pts[indices[i] - decal];
  50963. var p2 = pts[indices[i + 1] - decal];
  50964. var p3 = pts[indices[i + 2] - decal];
  50965. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50966. }
  50967. };
  50968. Collider.prototype._getResponse = function (pos, vel) {
  50969. pos.addToRef(vel, this._destinationPoint);
  50970. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50971. this._basePoint.addToRef(vel, pos);
  50972. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50973. this._slidePlaneNormal.normalize();
  50974. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50975. pos.addInPlace(this._displacementVector);
  50976. this.intersectionPoint.addInPlace(this._displacementVector);
  50977. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50978. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50979. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50980. };
  50981. return Collider;
  50982. }());
  50983. BABYLON.Collider = Collider;
  50984. })(BABYLON || (BABYLON = {}));
  50985. //# sourceMappingURL=babylon.collider.js.map
  50986. "use strict";
  50987. var BABYLON;
  50988. (function (BABYLON) {
  50989. //WebWorker code will be inserted to this variable.
  50990. BABYLON.CollisionWorker = "";
  50991. var WorkerTaskType;
  50992. (function (WorkerTaskType) {
  50993. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50994. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50995. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50996. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50997. var WorkerReplyType;
  50998. (function (WorkerReplyType) {
  50999. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51000. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51001. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51002. var CollisionCoordinatorWorker = /** @class */ (function () {
  51003. function CollisionCoordinatorWorker() {
  51004. var _this = this;
  51005. this._scaledPosition = BABYLON.Vector3.Zero();
  51006. this._scaledVelocity = BABYLON.Vector3.Zero();
  51007. this.onMeshUpdated = function (transformNode) {
  51008. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51009. };
  51010. this.onGeometryUpdated = function (geometry) {
  51011. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51012. };
  51013. this._afterRender = function () {
  51014. if (!_this._init)
  51015. return;
  51016. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51017. return;
  51018. }
  51019. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51020. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51021. if (_this._runningUpdated > 4) {
  51022. return;
  51023. }
  51024. ++_this._runningUpdated;
  51025. var payload = {
  51026. updatedMeshes: _this._addUpdateMeshesList,
  51027. updatedGeometries: _this._addUpdateGeometriesList,
  51028. removedGeometries: _this._toRemoveGeometryArray,
  51029. removedMeshes: _this._toRemoveMeshesArray
  51030. };
  51031. var message = {
  51032. payload: payload,
  51033. taskType: WorkerTaskType.UPDATE
  51034. };
  51035. var serializable = [];
  51036. for (var id in payload.updatedGeometries) {
  51037. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51038. //prepare transferables
  51039. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51040. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51041. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51042. }
  51043. }
  51044. _this._worker.postMessage(message, serializable);
  51045. _this._addUpdateMeshesList = {};
  51046. _this._addUpdateGeometriesList = {};
  51047. _this._toRemoveGeometryArray = [];
  51048. _this._toRemoveMeshesArray = [];
  51049. };
  51050. this._onMessageFromWorker = function (e) {
  51051. var returnData = e.data;
  51052. if (returnData.error != WorkerReplyType.SUCCESS) {
  51053. //TODO what errors can be returned from the worker?
  51054. BABYLON.Tools.Warn("error returned from worker!");
  51055. return;
  51056. }
  51057. switch (returnData.taskType) {
  51058. case WorkerTaskType.INIT:
  51059. _this._init = true;
  51060. //Update the worked with ALL of the scene's current state
  51061. _this._scene.meshes.forEach(function (mesh) {
  51062. _this.onMeshAdded(mesh);
  51063. });
  51064. _this._scene.getGeometries().forEach(function (geometry) {
  51065. _this.onGeometryAdded(geometry);
  51066. });
  51067. break;
  51068. case WorkerTaskType.UPDATE:
  51069. _this._runningUpdated--;
  51070. break;
  51071. case WorkerTaskType.COLLIDE:
  51072. var returnPayload = returnData.payload;
  51073. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51074. return;
  51075. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51076. if (callback) {
  51077. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51078. if (mesh) {
  51079. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51080. }
  51081. }
  51082. //cleanup
  51083. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51084. break;
  51085. }
  51086. };
  51087. this._collisionsCallbackArray = [];
  51088. this._init = false;
  51089. this._runningUpdated = 0;
  51090. this._addUpdateMeshesList = {};
  51091. this._addUpdateGeometriesList = {};
  51092. this._toRemoveGeometryArray = [];
  51093. this._toRemoveMeshesArray = [];
  51094. }
  51095. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51096. if (!this._init)
  51097. return;
  51098. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51099. return;
  51100. position.divideToRef(collider._radius, this._scaledPosition);
  51101. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51102. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51103. var payload = {
  51104. collider: {
  51105. position: this._scaledPosition.asArray(),
  51106. velocity: this._scaledVelocity.asArray(),
  51107. radius: collider._radius.asArray()
  51108. },
  51109. collisionId: collisionIndex,
  51110. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51111. maximumRetry: maximumRetry
  51112. };
  51113. var message = {
  51114. payload: payload,
  51115. taskType: WorkerTaskType.COLLIDE
  51116. };
  51117. this._worker.postMessage(message);
  51118. };
  51119. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51120. this._scene = scene;
  51121. this._scene.registerAfterRender(this._afterRender);
  51122. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51123. this._worker = new Worker(workerUrl);
  51124. this._worker.onmessage = this._onMessageFromWorker;
  51125. var message = {
  51126. payload: {},
  51127. taskType: WorkerTaskType.INIT
  51128. };
  51129. this._worker.postMessage(message);
  51130. };
  51131. CollisionCoordinatorWorker.prototype.destroy = function () {
  51132. this._scene.unregisterAfterRender(this._afterRender);
  51133. this._worker.terminate();
  51134. };
  51135. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51136. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51137. this.onMeshUpdated(mesh);
  51138. };
  51139. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51140. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51141. };
  51142. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51143. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51144. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51145. this.onGeometryUpdated(geometry);
  51146. };
  51147. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51148. this._toRemoveGeometryArray.push(geometry.id);
  51149. };
  51150. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51151. var submeshes = [];
  51152. if (mesh.subMeshes) {
  51153. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51154. var boundingInfo = sm.getBoundingInfo();
  51155. return {
  51156. position: idx,
  51157. verticesStart: sm.verticesStart,
  51158. verticesCount: sm.verticesCount,
  51159. indexStart: sm.indexStart,
  51160. indexCount: sm.indexCount,
  51161. hasMaterial: !!sm.getMaterial(),
  51162. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51163. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51164. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51165. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51166. };
  51167. });
  51168. }
  51169. var geometryId = null;
  51170. if (mesh instanceof BABYLON.Mesh) {
  51171. var geometry = mesh.geometry;
  51172. geometryId = geometry ? geometry.id : null;
  51173. }
  51174. else if (mesh instanceof BABYLON.InstancedMesh) {
  51175. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51176. geometryId = geometry ? geometry.id : null;
  51177. }
  51178. var boundingInfo = mesh.getBoundingInfo();
  51179. return {
  51180. uniqueId: mesh.uniqueId,
  51181. id: mesh.id,
  51182. name: mesh.name,
  51183. geometryId: geometryId,
  51184. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51185. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51186. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51187. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51188. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51189. subMeshes: submeshes,
  51190. checkCollisions: mesh.checkCollisions
  51191. };
  51192. };
  51193. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51194. return {
  51195. id: geometry.id,
  51196. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51197. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51198. indices: new Uint32Array(geometry.getIndices() || []),
  51199. };
  51200. };
  51201. return CollisionCoordinatorWorker;
  51202. }());
  51203. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51204. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51205. function CollisionCoordinatorLegacy() {
  51206. this._scaledPosition = BABYLON.Vector3.Zero();
  51207. this._scaledVelocity = BABYLON.Vector3.Zero();
  51208. this._finalPosition = BABYLON.Vector3.Zero();
  51209. }
  51210. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51211. position.divideToRef(collider._radius, this._scaledPosition);
  51212. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51213. collider.collidedMesh = null;
  51214. collider._retry = 0;
  51215. collider._initialVelocity = this._scaledVelocity;
  51216. collider._initialPosition = this._scaledPosition;
  51217. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51218. this._finalPosition.multiplyInPlace(collider._radius);
  51219. //run the callback
  51220. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51221. };
  51222. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51223. this._scene = scene;
  51224. };
  51225. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51226. //Legacy need no destruction method.
  51227. };
  51228. //No update in legacy mode
  51229. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51230. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51231. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51232. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51233. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51234. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51235. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51236. if (excludedMesh === void 0) { excludedMesh = null; }
  51237. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51238. if (collider._retry >= maximumRetry) {
  51239. finalPosition.copyFrom(position);
  51240. return;
  51241. }
  51242. // Check if this is a mesh else camera or -1
  51243. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51244. collider._initialize(position, velocity, closeDistance);
  51245. // Check all meshes
  51246. for (var index = 0; index < this._scene.meshes.length; index++) {
  51247. var mesh = this._scene.meshes[index];
  51248. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51249. mesh._checkCollision(collider);
  51250. }
  51251. }
  51252. if (!collider.collisionFound) {
  51253. position.addToRef(velocity, finalPosition);
  51254. return;
  51255. }
  51256. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51257. collider._getResponse(position, velocity);
  51258. }
  51259. if (velocity.length() <= closeDistance) {
  51260. finalPosition.copyFrom(position);
  51261. return;
  51262. }
  51263. collider._retry++;
  51264. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51265. };
  51266. return CollisionCoordinatorLegacy;
  51267. }());
  51268. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51269. })(BABYLON || (BABYLON = {}));
  51270. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51271. "use strict";
  51272. var BABYLON;
  51273. (function (BABYLON) {
  51274. /**
  51275. * A particle represents one of the element emitted by a particle system.
  51276. * This is mainly define by its coordinates, direction, velocity and age.
  51277. */
  51278. var Particle = /** @class */ (function () {
  51279. /**
  51280. * Creates a new instance of @see Particle
  51281. * @param particleSystem the particle system the particle belongs to
  51282. */
  51283. function Particle(
  51284. /**
  51285. * particleSystem the particle system the particle belongs to.
  51286. */
  51287. particleSystem) {
  51288. this.particleSystem = particleSystem;
  51289. /**
  51290. * The world position of the particle in the scene.
  51291. */
  51292. this.position = BABYLON.Vector3.Zero();
  51293. /**
  51294. * The world direction of the particle in the scene.
  51295. */
  51296. this.direction = BABYLON.Vector3.Zero();
  51297. /**
  51298. * The color of the particle.
  51299. */
  51300. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51301. /**
  51302. * The color change of the particle per step.
  51303. */
  51304. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51305. /**
  51306. * Defines how long will the life of the particle be.
  51307. */
  51308. this.lifeTime = 1.0;
  51309. /**
  51310. * The current age of the particle.
  51311. */
  51312. this.age = 0;
  51313. /**
  51314. * The current size of the particle.
  51315. */
  51316. this.size = 0;
  51317. /**
  51318. * The current angle of the particle.
  51319. */
  51320. this.angle = 0;
  51321. /**
  51322. * Defines how fast is the angle changing.
  51323. */
  51324. this.angularSpeed = 0;
  51325. /**
  51326. * Defines the cell index used by the particle to be rendered from a sprite.
  51327. */
  51328. this.cellIndex = 0;
  51329. this._currentFrameCounter = 0;
  51330. if (!this.particleSystem.isAnimationSheetEnabled) {
  51331. return;
  51332. }
  51333. this.updateCellInfoFromSystem();
  51334. }
  51335. Particle.prototype.updateCellInfoFromSystem = function () {
  51336. this.cellIndex = this.particleSystem.startSpriteCellID;
  51337. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51338. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51339. }
  51340. else {
  51341. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51342. }
  51343. };
  51344. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51345. // (ageOffset / scaledUpdateSpeed) / available cells
  51346. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51347. this._currentFrameCounter += scaledUpdateSpeed;
  51348. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51349. this._currentFrameCounter = 0;
  51350. this.cellIndex++;
  51351. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51352. this.cellIndex = this.particleSystem.endSpriteCellID;
  51353. }
  51354. }
  51355. };
  51356. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51357. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51358. this.cellIndex++;
  51359. this._currentFrameCounter = 0;
  51360. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51361. if (this.particleSystem.spriteCellLoop) {
  51362. this.cellIndex = this.particleSystem.startSpriteCellID;
  51363. }
  51364. else {
  51365. this.cellIndex = this.particleSystem.endSpriteCellID;
  51366. }
  51367. }
  51368. }
  51369. else {
  51370. this._currentFrameCounter++;
  51371. }
  51372. };
  51373. /**
  51374. * Copy the properties of particle to another one.
  51375. * @param other the particle to copy the information to.
  51376. */
  51377. Particle.prototype.copyTo = function (other) {
  51378. other.position.copyFrom(this.position);
  51379. other.direction.copyFrom(this.direction);
  51380. other.color.copyFrom(this.color);
  51381. other.colorStep.copyFrom(this.colorStep);
  51382. other.lifeTime = this.lifeTime;
  51383. other.age = this.age;
  51384. other.size = this.size;
  51385. other.angle = this.angle;
  51386. other.angularSpeed = this.angularSpeed;
  51387. other.particleSystem = this.particleSystem;
  51388. other.cellIndex = this.cellIndex;
  51389. };
  51390. return Particle;
  51391. }());
  51392. BABYLON.Particle = Particle;
  51393. })(BABYLON || (BABYLON = {}));
  51394. //# sourceMappingURL=babylon.particle.js.map
  51395. "use strict";
  51396. var BABYLON;
  51397. (function (BABYLON) {
  51398. /**
  51399. * This represents a particle system in Babylon.
  51400. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  51401. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51402. * @example https://doc.babylonjs.com/babylon101/particles
  51403. */
  51404. var ParticleSystem = /** @class */ (function () {
  51405. /**
  51406. * Instantiates a particle system.
  51407. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  51408. * @param name The name of the particle system
  51409. * @param capacity The max number of particles alive at the same time
  51410. * @param scene The scene the particle system belongs to
  51411. * @param customEffect a custom effect used to change the way particles are rendered by default
  51412. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51413. * @param epsilon Offset used to render the particles
  51414. */
  51415. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51416. if (customEffect === void 0) { customEffect = null; }
  51417. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51418. if (epsilon === void 0) { epsilon = 0.01; }
  51419. var _this = this;
  51420. /**
  51421. * List of animations used by the particle system.
  51422. */
  51423. this.animations = [];
  51424. /**
  51425. * The rendering group used by the Particle system to chose when to render.
  51426. */
  51427. this.renderingGroupId = 0;
  51428. /**
  51429. * The emitter represents the Mesh or position we are attaching the particle system to.
  51430. */
  51431. this.emitter = null;
  51432. /**
  51433. * The maximum number of particles to emit per frame
  51434. */
  51435. this.emitRate = 10;
  51436. /**
  51437. * If you want to launch only a few particles at once, that can be done, as well.
  51438. */
  51439. this.manualEmitCount = -1;
  51440. /**
  51441. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51442. */
  51443. this.updateSpeed = 0.01;
  51444. /**
  51445. * The amount of time the particle system is running (depends of the overall update speed).
  51446. */
  51447. this.targetStopDuration = 0;
  51448. /**
  51449. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51450. */
  51451. this.disposeOnStop = false;
  51452. /**
  51453. * Minimum power of emitting particles.
  51454. */
  51455. this.minEmitPower = 1;
  51456. /**
  51457. * Maximum power of emitting particles.
  51458. */
  51459. this.maxEmitPower = 1;
  51460. /**
  51461. * Minimum life time of emitting particles.
  51462. */
  51463. this.minLifeTime = 1;
  51464. /**
  51465. * Maximum life time of emitting particles.
  51466. */
  51467. this.maxLifeTime = 1;
  51468. /**
  51469. * Minimum Size of emitting particles.
  51470. */
  51471. this.minSize = 1;
  51472. /**
  51473. * Maximum Size of emitting particles.
  51474. */
  51475. this.maxSize = 1;
  51476. /**
  51477. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51478. */
  51479. this.minAngularSpeed = 0;
  51480. /**
  51481. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51482. */
  51483. this.maxAngularSpeed = 0;
  51484. /**
  51485. * The layer mask we are rendering the particles through.
  51486. */
  51487. this.layerMask = 0x0FFFFFFF;
  51488. /**
  51489. * This can help using your own shader to render the particle system.
  51490. * The according effect will be created
  51491. */
  51492. this.customShader = null;
  51493. /**
  51494. * By default particle system starts as soon as they are created. This prevents the
  51495. * automatic start to happen and let you decide when to start emitting particles.
  51496. */
  51497. this.preventAutoStart = false;
  51498. /**
  51499. * Callback triggered when the particle animation is ending.
  51500. */
  51501. this.onAnimationEnd = null;
  51502. /**
  51503. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51504. */
  51505. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51506. /**
  51507. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51508. * to override the particles.
  51509. */
  51510. this.forceDepthWrite = false;
  51511. /**
  51512. * You can use gravity if you want to give an orientation to your particles.
  51513. */
  51514. this.gravity = BABYLON.Vector3.Zero();
  51515. /**
  51516. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51517. */
  51518. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51519. /**
  51520. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51521. */
  51522. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51523. /**
  51524. * Color the particle will have at the end of its lifetime.
  51525. */
  51526. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51527. /**
  51528. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51529. */
  51530. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51531. /**
  51532. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51533. */
  51534. this.spriteCellLoop = true;
  51535. /**
  51536. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51537. */
  51538. this.spriteCellChangeSpeed = 0;
  51539. /**
  51540. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51541. */
  51542. this.startSpriteCellID = 0;
  51543. /**
  51544. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51545. */
  51546. this.endSpriteCellID = 0;
  51547. /**
  51548. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51549. */
  51550. this.spriteCellWidth = 0;
  51551. /**
  51552. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51553. */
  51554. this.spriteCellHeight = 0;
  51555. /**
  51556. * An event triggered when the system is disposed.
  51557. */
  51558. this.onDisposeObservable = new BABYLON.Observable();
  51559. this._particles = new Array();
  51560. this._stockParticles = new Array();
  51561. this._newPartsExcess = 0;
  51562. this._vertexBuffers = {};
  51563. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51564. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51565. this._scaledDirection = BABYLON.Vector3.Zero();
  51566. this._scaledGravity = BABYLON.Vector3.Zero();
  51567. this._currentRenderId = -1;
  51568. this._started = false;
  51569. this._stopped = false;
  51570. this._actualFrame = 0;
  51571. this._vertexBufferSize = 11;
  51572. // start of sub system methods
  51573. /**
  51574. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51575. * Its lifetime will start back at 0.
  51576. */
  51577. this.recycleParticle = function (particle) {
  51578. var lastParticle = _this._particles.pop();
  51579. if (lastParticle !== particle) {
  51580. lastParticle.copyTo(particle);
  51581. }
  51582. _this._stockParticles.push(lastParticle);
  51583. };
  51584. this._createParticle = function () {
  51585. var particle;
  51586. if (_this._stockParticles.length !== 0) {
  51587. particle = _this._stockParticles.pop();
  51588. particle.age = 0;
  51589. particle.cellIndex = _this.startSpriteCellID;
  51590. }
  51591. else {
  51592. particle = new BABYLON.Particle(_this);
  51593. }
  51594. return particle;
  51595. };
  51596. this._emitFromParticle = function (particle) {
  51597. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51598. return;
  51599. }
  51600. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51601. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51602. subSystem._rootParticleSystem = _this;
  51603. _this.activeSubSystems.push(subSystem);
  51604. subSystem.start();
  51605. };
  51606. this._appendParticleVertexes = null;
  51607. this.id = name;
  51608. this.name = name;
  51609. this._capacity = capacity;
  51610. this._epsilon = epsilon;
  51611. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51612. if (isAnimationSheetEnabled) {
  51613. this._vertexBufferSize = 12;
  51614. }
  51615. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51616. this._customEffect = customEffect;
  51617. scene.particleSystems.push(this);
  51618. this._createIndexBuffer();
  51619. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51620. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51621. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51622. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51623. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51624. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51625. if (this._isAnimationSheetEnabled) {
  51626. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51627. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51628. }
  51629. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51630. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51631. this._vertexBuffers["options"] = options;
  51632. // Default emitter type
  51633. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51634. this.updateFunction = function (particles) {
  51635. for (var index = 0; index < particles.length; index++) {
  51636. var particle = particles[index];
  51637. particle.age += _this._scaledUpdateSpeed;
  51638. if (particle.age >= particle.lifeTime) {
  51639. _this._emitFromParticle(particle);
  51640. _this.recycleParticle(particle);
  51641. index--;
  51642. continue;
  51643. }
  51644. else {
  51645. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51646. particle.color.addInPlace(_this._scaledColorStep);
  51647. if (particle.color.a < 0)
  51648. particle.color.a = 0;
  51649. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51650. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51651. particle.position.addInPlace(_this._scaledDirection);
  51652. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51653. particle.direction.addInPlace(_this._scaledGravity);
  51654. if (_this._isAnimationSheetEnabled) {
  51655. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51656. }
  51657. }
  51658. }
  51659. };
  51660. }
  51661. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51662. /**
  51663. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51664. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51665. */
  51666. get: function () {
  51667. if (this.particleEmitterType.direction1) {
  51668. return this.particleEmitterType.direction1;
  51669. }
  51670. return BABYLON.Vector3.Zero();
  51671. },
  51672. set: function (value) {
  51673. if (this.particleEmitterType.direction1) {
  51674. this.particleEmitterType.direction1 = value;
  51675. }
  51676. },
  51677. enumerable: true,
  51678. configurable: true
  51679. });
  51680. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51681. /**
  51682. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51683. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51684. */
  51685. get: function () {
  51686. if (this.particleEmitterType.direction2) {
  51687. return this.particleEmitterType.direction2;
  51688. }
  51689. return BABYLON.Vector3.Zero();
  51690. },
  51691. set: function (value) {
  51692. if (this.particleEmitterType.direction2) {
  51693. this.particleEmitterType.direction2 = value;
  51694. }
  51695. },
  51696. enumerable: true,
  51697. configurable: true
  51698. });
  51699. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51700. /**
  51701. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  51702. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51703. */
  51704. get: function () {
  51705. if (this.particleEmitterType.minEmitBox) {
  51706. return this.particleEmitterType.minEmitBox;
  51707. }
  51708. return BABYLON.Vector3.Zero();
  51709. },
  51710. set: function (value) {
  51711. if (this.particleEmitterType.minEmitBox) {
  51712. this.particleEmitterType.minEmitBox = value;
  51713. }
  51714. },
  51715. enumerable: true,
  51716. configurable: true
  51717. });
  51718. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51719. /**
  51720. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  51721. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51722. */
  51723. get: function () {
  51724. if (this.particleEmitterType.maxEmitBox) {
  51725. return this.particleEmitterType.maxEmitBox;
  51726. }
  51727. return BABYLON.Vector3.Zero();
  51728. },
  51729. set: function (value) {
  51730. if (this.particleEmitterType.maxEmitBox) {
  51731. this.particleEmitterType.maxEmitBox = value;
  51732. }
  51733. },
  51734. enumerable: true,
  51735. configurable: true
  51736. });
  51737. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51738. /**
  51739. * Sets a callback that will be triggered when the system is disposed.
  51740. */
  51741. set: function (callback) {
  51742. if (this._onDisposeObserver) {
  51743. this.onDisposeObservable.remove(this._onDisposeObserver);
  51744. }
  51745. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51746. },
  51747. enumerable: true,
  51748. configurable: true
  51749. });
  51750. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51751. /**
  51752. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51753. */
  51754. get: function () {
  51755. return this._isAnimationSheetEnabled;
  51756. },
  51757. enumerable: true,
  51758. configurable: true
  51759. });
  51760. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51761. //end of Sub-emitter
  51762. /**
  51763. * Gets the current list of active particles
  51764. */
  51765. get: function () {
  51766. return this._particles;
  51767. },
  51768. enumerable: true,
  51769. configurable: true
  51770. });
  51771. /**
  51772. * Returns the string "ParticleSystem"
  51773. * @returns a string containing the class name
  51774. */
  51775. ParticleSystem.prototype.getClassName = function () {
  51776. return "ParticleSystem";
  51777. };
  51778. ParticleSystem.prototype._createIndexBuffer = function () {
  51779. var indices = [];
  51780. var index = 0;
  51781. for (var count = 0; count < this._capacity; count++) {
  51782. indices.push(index);
  51783. indices.push(index + 1);
  51784. indices.push(index + 2);
  51785. indices.push(index);
  51786. indices.push(index + 2);
  51787. indices.push(index + 3);
  51788. index += 4;
  51789. }
  51790. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51791. };
  51792. /**
  51793. * Gets the maximum number of particles active at the same time.
  51794. * @returns The max number of active particles.
  51795. */
  51796. ParticleSystem.prototype.getCapacity = function () {
  51797. return this._capacity;
  51798. };
  51799. /**
  51800. * Gets Wether there are still active particles in the system.
  51801. * @returns True if it is alive, otherwise false.
  51802. */
  51803. ParticleSystem.prototype.isAlive = function () {
  51804. return this._alive;
  51805. };
  51806. /**
  51807. * Gets Wether the system has been started.
  51808. * @returns True if it has been started, otherwise false.
  51809. */
  51810. ParticleSystem.prototype.isStarted = function () {
  51811. return this._started;
  51812. };
  51813. /**
  51814. * Starts the particle system and begins to emit.
  51815. */
  51816. ParticleSystem.prototype.start = function () {
  51817. this._started = true;
  51818. this._stopped = false;
  51819. this._actualFrame = 0;
  51820. if (this.subEmitters && this.subEmitters.length != 0) {
  51821. this.activeSubSystems = new Array();
  51822. }
  51823. };
  51824. /**
  51825. * Stops the particle system.
  51826. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
  51827. */
  51828. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51829. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51830. this._stopped = true;
  51831. if (stopSubEmitters) {
  51832. this._stopSubEmitters();
  51833. }
  51834. };
  51835. // animation sheet
  51836. /**
  51837. * Remove all active particles
  51838. */
  51839. ParticleSystem.prototype.reset = function () {
  51840. this._stockParticles = [];
  51841. this._particles = [];
  51842. };
  51843. /**
  51844. * @ignore (for internal use only)
  51845. */
  51846. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51847. var offset = index * this._vertexBufferSize;
  51848. this._vertexData[offset] = particle.position.x;
  51849. this._vertexData[offset + 1] = particle.position.y;
  51850. this._vertexData[offset + 2] = particle.position.z;
  51851. this._vertexData[offset + 3] = particle.color.r;
  51852. this._vertexData[offset + 4] = particle.color.g;
  51853. this._vertexData[offset + 5] = particle.color.b;
  51854. this._vertexData[offset + 6] = particle.color.a;
  51855. this._vertexData[offset + 7] = particle.angle;
  51856. this._vertexData[offset + 8] = particle.size;
  51857. this._vertexData[offset + 9] = offsetX;
  51858. this._vertexData[offset + 10] = offsetY;
  51859. };
  51860. /**
  51861. * @ignore (for internal use only)
  51862. */
  51863. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51864. if (offsetX === 0)
  51865. offsetX = this._epsilon;
  51866. else if (offsetX === 1)
  51867. offsetX = 1 - this._epsilon;
  51868. if (offsetY === 0)
  51869. offsetY = this._epsilon;
  51870. else if (offsetY === 1)
  51871. offsetY = 1 - this._epsilon;
  51872. var offset = index * this._vertexBufferSize;
  51873. this._vertexData[offset] = particle.position.x;
  51874. this._vertexData[offset + 1] = particle.position.y;
  51875. this._vertexData[offset + 2] = particle.position.z;
  51876. this._vertexData[offset + 3] = particle.color.r;
  51877. this._vertexData[offset + 4] = particle.color.g;
  51878. this._vertexData[offset + 5] = particle.color.b;
  51879. this._vertexData[offset + 6] = particle.color.a;
  51880. this._vertexData[offset + 7] = particle.angle;
  51881. this._vertexData[offset + 8] = particle.size;
  51882. this._vertexData[offset + 9] = offsetX;
  51883. this._vertexData[offset + 10] = offsetY;
  51884. this._vertexData[offset + 11] = particle.cellIndex;
  51885. };
  51886. ParticleSystem.prototype._stopSubEmitters = function () {
  51887. if (!this.activeSubSystems) {
  51888. return;
  51889. }
  51890. this.activeSubSystems.forEach(function (subSystem) {
  51891. subSystem.stop(true);
  51892. });
  51893. this.activeSubSystems = new Array();
  51894. };
  51895. ParticleSystem.prototype._removeFromRoot = function () {
  51896. if (!this._rootParticleSystem) {
  51897. return;
  51898. }
  51899. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51900. if (index !== -1) {
  51901. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51902. }
  51903. };
  51904. // end of sub system methods
  51905. ParticleSystem.prototype._update = function (newParticles) {
  51906. // Update current
  51907. this._alive = this._particles.length > 0;
  51908. this.updateFunction(this._particles);
  51909. // Add new ones
  51910. var worldMatrix;
  51911. if (this.emitter.position) {
  51912. var emitterMesh = this.emitter;
  51913. worldMatrix = emitterMesh.getWorldMatrix();
  51914. }
  51915. else {
  51916. var emitterPosition = this.emitter;
  51917. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51918. }
  51919. var particle;
  51920. for (var index = 0; index < newParticles; index++) {
  51921. if (this._particles.length === this._capacity) {
  51922. break;
  51923. }
  51924. particle = this._createParticle();
  51925. this._particles.push(particle);
  51926. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51927. if (this.startPositionFunction) {
  51928. this.startPositionFunction(worldMatrix, particle.position, particle);
  51929. }
  51930. else {
  51931. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51932. }
  51933. if (this.startDirectionFunction) {
  51934. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51935. }
  51936. else {
  51937. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51938. }
  51939. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51940. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51941. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51942. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51943. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51944. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51945. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51946. }
  51947. };
  51948. ParticleSystem.prototype._getEffect = function () {
  51949. if (this._customEffect) {
  51950. return this._customEffect;
  51951. }
  51952. ;
  51953. var defines = [];
  51954. if (this._scene.clipPlane) {
  51955. defines.push("#define CLIPPLANE");
  51956. }
  51957. if (this._isAnimationSheetEnabled) {
  51958. defines.push("#define ANIMATESHEET");
  51959. }
  51960. // Effect
  51961. var join = defines.join("\n");
  51962. if (this._cachedDefines !== join) {
  51963. this._cachedDefines = join;
  51964. var attributesNamesOrOptions;
  51965. var effectCreationOption;
  51966. if (this._isAnimationSheetEnabled) {
  51967. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51968. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51969. }
  51970. else {
  51971. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51972. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51973. }
  51974. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51975. }
  51976. return this._effect;
  51977. };
  51978. /**
  51979. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51980. */
  51981. ParticleSystem.prototype.animate = function () {
  51982. if (!this._started)
  51983. return;
  51984. var effect = this._getEffect();
  51985. // Check
  51986. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51987. return;
  51988. if (this._currentRenderId === this._scene.getRenderId()) {
  51989. return;
  51990. }
  51991. this._currentRenderId = this._scene.getRenderId();
  51992. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51993. // determine the number of particles we need to create
  51994. var newParticles;
  51995. if (this.manualEmitCount > -1) {
  51996. newParticles = this.manualEmitCount;
  51997. this._newPartsExcess = 0;
  51998. this.manualEmitCount = 0;
  51999. }
  52000. else {
  52001. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52002. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52003. }
  52004. if (this._newPartsExcess > 1.0) {
  52005. newParticles += this._newPartsExcess >> 0;
  52006. this._newPartsExcess -= this._newPartsExcess >> 0;
  52007. }
  52008. this._alive = false;
  52009. if (!this._stopped) {
  52010. this._actualFrame += this._scaledUpdateSpeed;
  52011. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52012. this.stop();
  52013. }
  52014. else {
  52015. newParticles = 0;
  52016. }
  52017. this._update(newParticles);
  52018. // Stopped?
  52019. if (this._stopped) {
  52020. if (!this._alive) {
  52021. this._started = false;
  52022. if (this.onAnimationEnd) {
  52023. this.onAnimationEnd();
  52024. }
  52025. if (this.disposeOnStop) {
  52026. this._scene._toBeDisposed.push(this);
  52027. }
  52028. }
  52029. }
  52030. // Animation sheet
  52031. if (this._isAnimationSheetEnabled) {
  52032. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52033. }
  52034. else {
  52035. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52036. }
  52037. // Update VBO
  52038. var offset = 0;
  52039. for (var index = 0; index < this._particles.length; index++) {
  52040. var particle = this._particles[index];
  52041. this._appendParticleVertexes(offset, particle);
  52042. offset += 4;
  52043. }
  52044. if (this._vertexBuffer) {
  52045. this._vertexBuffer.update(this._vertexData);
  52046. }
  52047. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52048. this.stop();
  52049. }
  52050. };
  52051. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52052. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52053. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52054. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52055. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52056. };
  52057. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52058. this._appendParticleVertex(offset++, particle, 0, 0);
  52059. this._appendParticleVertex(offset++, particle, 1, 0);
  52060. this._appendParticleVertex(offset++, particle, 1, 1);
  52061. this._appendParticleVertex(offset++, particle, 0, 1);
  52062. };
  52063. /**
  52064. * Rebuilds the particle system.
  52065. */
  52066. ParticleSystem.prototype.rebuild = function () {
  52067. this._createIndexBuffer();
  52068. if (this._vertexBuffer) {
  52069. this._vertexBuffer._rebuild();
  52070. }
  52071. };
  52072. /**
  52073. * Is this system ready to be used/rendered
  52074. * @return true if the system is ready
  52075. */
  52076. ParticleSystem.prototype.isReady = function () {
  52077. var effect = this._getEffect();
  52078. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52079. return false;
  52080. }
  52081. return true;
  52082. };
  52083. /**
  52084. * Renders the particle system in its current state.
  52085. * @returns the current number of particles
  52086. */
  52087. ParticleSystem.prototype.render = function () {
  52088. var effect = this._getEffect();
  52089. // Check
  52090. if (!this.isReady() || !this._particles.length) {
  52091. return 0;
  52092. }
  52093. var engine = this._scene.getEngine();
  52094. // Render
  52095. engine.enableEffect(effect);
  52096. engine.setState(false);
  52097. var viewMatrix = this._scene.getViewMatrix();
  52098. effect.setTexture("diffuseSampler", this.particleTexture);
  52099. effect.setMatrix("view", viewMatrix);
  52100. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52101. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52102. var baseSize = this.particleTexture.getBaseSize();
  52103. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52104. }
  52105. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52106. if (this._scene.clipPlane) {
  52107. var clipPlane = this._scene.clipPlane;
  52108. var invView = viewMatrix.clone();
  52109. invView.invert();
  52110. effect.setMatrix("invView", invView);
  52111. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52112. }
  52113. // VBOs
  52114. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52115. // Draw order
  52116. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52117. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52118. }
  52119. else {
  52120. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52121. }
  52122. if (this.forceDepthWrite) {
  52123. engine.setDepthWrite(true);
  52124. }
  52125. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52126. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52127. return this._particles.length;
  52128. };
  52129. /**
  52130. * Disposes the particle system and free the associated resources
  52131. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52132. */
  52133. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52134. if (disposeTexture === void 0) { disposeTexture = true; }
  52135. if (this._vertexBuffer) {
  52136. this._vertexBuffer.dispose();
  52137. this._vertexBuffer = null;
  52138. }
  52139. if (this._indexBuffer) {
  52140. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52141. this._indexBuffer = null;
  52142. }
  52143. if (disposeTexture && this.particleTexture) {
  52144. this.particleTexture.dispose();
  52145. this.particleTexture = null;
  52146. }
  52147. this._removeFromRoot();
  52148. // Remove from scene
  52149. var index = this._scene.particleSystems.indexOf(this);
  52150. if (index > -1) {
  52151. this._scene.particleSystems.splice(index, 1);
  52152. }
  52153. // Callback
  52154. this.onDisposeObservable.notifyObservers(this);
  52155. this.onDisposeObservable.clear();
  52156. };
  52157. /**
  52158. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52159. * @param radius The radius of the sphere to emit from
  52160. * @returns the emitter
  52161. */
  52162. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52163. if (radius === void 0) { radius = 1; }
  52164. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52165. this.particleEmitterType = particleEmitter;
  52166. return particleEmitter;
  52167. };
  52168. /**
  52169. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52170. * @param radius The radius of the sphere to emit from
  52171. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52172. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52173. * @returns the emitter
  52174. */
  52175. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52176. if (radius === void 0) { radius = 1; }
  52177. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52178. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52179. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52180. this.particleEmitterType = particleEmitter;
  52181. return particleEmitter;
  52182. };
  52183. /**
  52184. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52185. * @param radius The radius of the cone to emit from
  52186. * @param angle The base angle of the cone
  52187. * @returns the emitter
  52188. */
  52189. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52190. if (radius === void 0) { radius = 1; }
  52191. if (angle === void 0) { angle = Math.PI / 4; }
  52192. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52193. this.particleEmitterType = particleEmitter;
  52194. return particleEmitter;
  52195. };
  52196. // 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.
  52197. /**
  52198. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52199. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52200. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52201. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52202. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52203. * @returns the emitter
  52204. */
  52205. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52206. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52207. this.direction1 = direction1;
  52208. this.direction2 = direction2;
  52209. this.minEmitBox = minEmitBox;
  52210. this.maxEmitBox = maxEmitBox;
  52211. this.particleEmitterType = particleEmitter;
  52212. return particleEmitter;
  52213. };
  52214. // Clone
  52215. /**
  52216. * Clones the particle system.
  52217. * @param name The name of the cloned object
  52218. * @param newEmitter The new emitter to use
  52219. * @returns the cloned particle system
  52220. */
  52221. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52222. var custom = null;
  52223. var program = null;
  52224. if (this.customShader != null) {
  52225. program = this.customShader;
  52226. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52227. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52228. }
  52229. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52230. result.customShader = program;
  52231. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52232. if (newEmitter === undefined) {
  52233. newEmitter = this.emitter;
  52234. }
  52235. result.emitter = newEmitter;
  52236. if (this.particleTexture) {
  52237. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52238. }
  52239. if (!this.preventAutoStart) {
  52240. result.start();
  52241. }
  52242. return result;
  52243. };
  52244. /**
  52245. * Serializes the particle system to a JSON object.
  52246. * @returns the JSON object
  52247. */
  52248. ParticleSystem.prototype.serialize = function () {
  52249. var serializationObject = {};
  52250. serializationObject.name = this.name;
  52251. serializationObject.id = this.id;
  52252. // Emitter
  52253. if (this.emitter.position) {
  52254. var emitterMesh = this.emitter;
  52255. serializationObject.emitterId = emitterMesh.id;
  52256. }
  52257. else {
  52258. var emitterPosition = this.emitter;
  52259. serializationObject.emitter = emitterPosition.asArray();
  52260. }
  52261. serializationObject.capacity = this.getCapacity();
  52262. if (this.particleTexture) {
  52263. serializationObject.textureName = this.particleTexture.name;
  52264. }
  52265. // Animations
  52266. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52267. // Particle system
  52268. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52269. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52270. serializationObject.minSize = this.minSize;
  52271. serializationObject.maxSize = this.maxSize;
  52272. serializationObject.minEmitPower = this.minEmitPower;
  52273. serializationObject.maxEmitPower = this.maxEmitPower;
  52274. serializationObject.minLifeTime = this.minLifeTime;
  52275. serializationObject.maxLifeTime = this.maxLifeTime;
  52276. serializationObject.emitRate = this.emitRate;
  52277. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52278. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52279. serializationObject.gravity = this.gravity.asArray();
  52280. serializationObject.direction1 = this.direction1.asArray();
  52281. serializationObject.direction2 = this.direction2.asArray();
  52282. serializationObject.color1 = this.color1.asArray();
  52283. serializationObject.color2 = this.color2.asArray();
  52284. serializationObject.colorDead = this.colorDead.asArray();
  52285. serializationObject.updateSpeed = this.updateSpeed;
  52286. serializationObject.targetStopDuration = this.targetStopDuration;
  52287. serializationObject.textureMask = this.textureMask.asArray();
  52288. serializationObject.blendMode = this.blendMode;
  52289. serializationObject.customShader = this.customShader;
  52290. serializationObject.preventAutoStart = this.preventAutoStart;
  52291. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52292. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52293. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52294. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52295. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52296. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52297. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52298. // Emitter
  52299. if (this.particleEmitterType) {
  52300. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52301. }
  52302. return serializationObject;
  52303. };
  52304. /**
  52305. * Parses a JSON object to create a particle system.
  52306. * @param parsedParticleSystem The JSON object to parse
  52307. * @param scene The scene to create the particle system in
  52308. * @param rootUrl The root url to use to load external dependencies like texture
  52309. * @returns the Parsed particle system
  52310. */
  52311. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52312. var name = parsedParticleSystem.name;
  52313. var custom = null;
  52314. var program = null;
  52315. if (parsedParticleSystem.customShader) {
  52316. program = parsedParticleSystem.customShader;
  52317. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52318. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52319. }
  52320. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52321. particleSystem.customShader = program;
  52322. if (parsedParticleSystem.id) {
  52323. particleSystem.id = parsedParticleSystem.id;
  52324. }
  52325. // Auto start
  52326. if (parsedParticleSystem.preventAutoStart) {
  52327. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52328. }
  52329. // Texture
  52330. if (parsedParticleSystem.textureName) {
  52331. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52332. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52333. }
  52334. // Emitter
  52335. if (parsedParticleSystem.emitterId) {
  52336. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52337. }
  52338. else {
  52339. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52340. }
  52341. // Animations
  52342. if (parsedParticleSystem.animations) {
  52343. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52344. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52345. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52346. }
  52347. }
  52348. if (parsedParticleSystem.autoAnimate) {
  52349. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52350. }
  52351. // Particle system
  52352. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52353. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52354. particleSystem.minSize = parsedParticleSystem.minSize;
  52355. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52356. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52357. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52358. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52359. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52360. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52361. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52362. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52363. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52364. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52365. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52366. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52367. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52368. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52369. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52370. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52371. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52372. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52373. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52374. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52375. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52376. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52377. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52378. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52379. if (!particleSystem.preventAutoStart) {
  52380. particleSystem.start();
  52381. }
  52382. return particleSystem;
  52383. };
  52384. /**
  52385. * Source color is added to the destination color without alpha affecting the result.
  52386. */
  52387. ParticleSystem.BLENDMODE_ONEONE = 0;
  52388. /**
  52389. * Blend current color and particle color using particle’s alpha.
  52390. */
  52391. ParticleSystem.BLENDMODE_STANDARD = 1;
  52392. return ParticleSystem;
  52393. }());
  52394. BABYLON.ParticleSystem = ParticleSystem;
  52395. })(BABYLON || (BABYLON = {}));
  52396. //# sourceMappingURL=babylon.particleSystem.js.map
  52397. "use strict";
  52398. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52399. "use strict";
  52400. var BABYLON;
  52401. (function (BABYLON) {
  52402. /**
  52403. * Particle emitter emitting particles from the inside of a box.
  52404. * It emits the particles randomly between 2 given directions.
  52405. */
  52406. var BoxParticleEmitter = /** @class */ (function () {
  52407. /**
  52408. * Creates a new instance of @see BoxParticleEmitter
  52409. */
  52410. function BoxParticleEmitter() {
  52411. /**
  52412. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52413. */
  52414. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52415. /**
  52416. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52417. */
  52418. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52419. /**
  52420. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  52421. */
  52422. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52423. /**
  52424. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  52425. */
  52426. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52427. }
  52428. /**
  52429. * Called by the particle System when the direction is computed for the created particle.
  52430. * @param emitPower is the power of the particle (speed)
  52431. * @param worldMatrix is the world matrix of the particle system
  52432. * @param directionToUpdate is the direction vector to update with the result
  52433. * @param particle is the particle we are computed the direction for
  52434. */
  52435. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52436. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52437. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52438. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52439. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52440. };
  52441. /**
  52442. * Called by the particle System when the position is computed for the created particle.
  52443. * @param worldMatrix is the world matrix of the particle system
  52444. * @param positionToUpdate is the position vector to update with the result
  52445. * @param particle is the particle we are computed the position for
  52446. */
  52447. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52448. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52449. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52450. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52451. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52452. };
  52453. /**
  52454. * Clones the current emitter and returns a copy of it
  52455. * @returns the new emitter
  52456. */
  52457. BoxParticleEmitter.prototype.clone = function () {
  52458. var newOne = new BoxParticleEmitter();
  52459. BABYLON.Tools.DeepCopy(this, newOne);
  52460. return newOne;
  52461. };
  52462. /**
  52463. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52464. * @param effect defines the update shader
  52465. */
  52466. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52467. effect.setVector3("direction1", this.direction1);
  52468. effect.setVector3("direction2", this.direction2);
  52469. effect.setVector3("minEmitBox", this.minEmitBox);
  52470. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52471. };
  52472. /**
  52473. * Returns a string to use to update the GPU particles update shader
  52474. * @returns a string containng the defines string
  52475. */
  52476. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52477. return "#define BOXEMITTER";
  52478. };
  52479. /**
  52480. * Returns the string "BoxEmitter"
  52481. * @returns a string containing the class name
  52482. */
  52483. BoxParticleEmitter.prototype.getClassName = function () {
  52484. return "BoxEmitter";
  52485. };
  52486. /**
  52487. * Serializes the particle system to a JSON object.
  52488. * @returns the JSON object
  52489. */
  52490. BoxParticleEmitter.prototype.serialize = function () {
  52491. var serializationObject = {};
  52492. serializationObject.type = this.getClassName();
  52493. serializationObject.direction1 = this.direction1.asArray();
  52494. ;
  52495. serializationObject.direction2 = this.direction2.asArray();
  52496. ;
  52497. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52498. ;
  52499. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52500. ;
  52501. return serializationObject;
  52502. };
  52503. /**
  52504. * Parse properties from a JSON object
  52505. * @param serializationObject defines the JSON object
  52506. */
  52507. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52508. this.direction1.copyFrom(serializationObject.direction1);
  52509. this.direction2.copyFrom(serializationObject.direction2);
  52510. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52511. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52512. };
  52513. return BoxParticleEmitter;
  52514. }());
  52515. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52516. })(BABYLON || (BABYLON = {}));
  52517. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52518. "use strict";
  52519. var BABYLON;
  52520. (function (BABYLON) {
  52521. /**
  52522. * Particle emitter emitting particles from the inside of a cone.
  52523. * It emits the particles alongside the cone volume from the base to the particle.
  52524. * The emission direction might be randomized.
  52525. */
  52526. var ConeParticleEmitter = /** @class */ (function () {
  52527. /**
  52528. * Creates a new instance of @see ConeParticleEmitter
  52529. * @param radius the radius of the emission cone (1 by default)
  52530. * @param angles the cone base angle (PI by default)
  52531. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52532. */
  52533. function ConeParticleEmitter(radius,
  52534. /**
  52535. * The radius of the emission cone.
  52536. */
  52537. angle,
  52538. /**
  52539. * The cone base angle.
  52540. */
  52541. directionRandomizer) {
  52542. if (radius === void 0) { radius = 1; }
  52543. if (angle === void 0) { angle = Math.PI; }
  52544. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52545. this.angle = angle;
  52546. this.directionRandomizer = directionRandomizer;
  52547. this.radius = radius;
  52548. }
  52549. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52550. /**
  52551. * Gets the radius of the emission cone.
  52552. */
  52553. get: function () {
  52554. return this._radius;
  52555. },
  52556. /**
  52557. * Sets the radius of the emission cone.
  52558. */
  52559. set: function (value) {
  52560. this._radius = value;
  52561. if (this.angle !== 0) {
  52562. this._height = value / Math.tan(this.angle / 2);
  52563. }
  52564. else {
  52565. this._height = 1;
  52566. }
  52567. },
  52568. enumerable: true,
  52569. configurable: true
  52570. });
  52571. /**
  52572. * Called by the particle System when the direction is computed for the created particle.
  52573. * @param emitPower is the power of the particle (speed)
  52574. * @param worldMatrix is the world matrix of the particle system
  52575. * @param directionToUpdate is the direction vector to update with the result
  52576. * @param particle is the particle we are computed the direction for
  52577. */
  52578. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52579. if (this.angle === 0) {
  52580. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52581. }
  52582. else {
  52583. // measure the direction Vector from the emitter to the particle.
  52584. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52585. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52586. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52587. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52588. direction.x += randX;
  52589. direction.y += randY;
  52590. direction.z += randZ;
  52591. direction.normalize();
  52592. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52593. }
  52594. };
  52595. /**
  52596. * Called by the particle System when the position is computed for the created particle.
  52597. * @param worldMatrix is the world matrix of the particle system
  52598. * @param positionToUpdate is the position vector to update with the result
  52599. * @param particle is the particle we are computed the position for
  52600. */
  52601. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52602. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52603. var h = BABYLON.Scalar.RandomRange(0, 1);
  52604. // Better distribution in a cone at normal angles.
  52605. h = 1 - h * h;
  52606. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52607. radius = radius * h / this._height;
  52608. var randX = radius * Math.sin(s);
  52609. var randZ = radius * Math.cos(s);
  52610. var randY = h * this._height;
  52611. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52612. };
  52613. /**
  52614. * Clones the current emitter and returns a copy of it
  52615. * @returns the new emitter
  52616. */
  52617. ConeParticleEmitter.prototype.clone = function () {
  52618. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52619. BABYLON.Tools.DeepCopy(this, newOne);
  52620. return newOne;
  52621. };
  52622. /**
  52623. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52624. * @param effect defines the update shader
  52625. */
  52626. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52627. effect.setFloat("radius", this.radius);
  52628. effect.setFloat("angle", this.angle);
  52629. effect.setFloat("height", this._height);
  52630. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52631. };
  52632. /**
  52633. * Returns a string to use to update the GPU particles update shader
  52634. * @returns a string containng the defines string
  52635. */
  52636. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52637. return "#define CONEEMITTER";
  52638. };
  52639. /**
  52640. * Returns the string "BoxEmitter"
  52641. * @returns a string containing the class name
  52642. */
  52643. ConeParticleEmitter.prototype.getClassName = function () {
  52644. return "ConeEmitter";
  52645. };
  52646. /**
  52647. * Serializes the particle system to a JSON object.
  52648. * @returns the JSON object
  52649. */
  52650. ConeParticleEmitter.prototype.serialize = function () {
  52651. var serializationObject = {};
  52652. serializationObject.type = this.getClassName();
  52653. serializationObject.radius = this.radius;
  52654. serializationObject.angle = this.angle;
  52655. serializationObject.directionRandomizer = this.directionRandomizer;
  52656. return serializationObject;
  52657. };
  52658. /**
  52659. * Parse properties from a JSON object
  52660. * @param serializationObject defines the JSON object
  52661. */
  52662. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52663. this.radius = serializationObject.radius;
  52664. this.angle = serializationObject.angle;
  52665. this.directionRandomizer = serializationObject.directionRandomizer;
  52666. };
  52667. return ConeParticleEmitter;
  52668. }());
  52669. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52670. })(BABYLON || (BABYLON = {}));
  52671. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52672. "use strict";
  52673. var BABYLON;
  52674. (function (BABYLON) {
  52675. /**
  52676. * Particle emitter emitting particles from the inside of a sphere.
  52677. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52678. */
  52679. var SphereParticleEmitter = /** @class */ (function () {
  52680. /**
  52681. * Creates a new instance of @see SphereParticleEmitter
  52682. * @param radius the radius of the emission sphere (1 by default)
  52683. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52684. */
  52685. function SphereParticleEmitter(
  52686. /**
  52687. * The radius of the emission sphere.
  52688. */
  52689. radius,
  52690. /**
  52691. * How much to randomize the particle direction [0-1].
  52692. */
  52693. directionRandomizer) {
  52694. if (radius === void 0) { radius = 1; }
  52695. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52696. this.radius = radius;
  52697. this.directionRandomizer = directionRandomizer;
  52698. }
  52699. /**
  52700. * Called by the particle System when the direction is computed for the created particle.
  52701. * @param emitPower is the power of the particle (speed)
  52702. * @param worldMatrix is the world matrix of the particle system
  52703. * @param directionToUpdate is the direction vector to update with the result
  52704. * @param particle is the particle we are computed the direction for
  52705. */
  52706. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52707. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52708. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52709. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52710. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52711. direction.x += randX;
  52712. direction.y += randY;
  52713. direction.z += randZ;
  52714. direction.normalize();
  52715. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52716. };
  52717. /**
  52718. * Called by the particle System when the position is computed for the created particle.
  52719. * @param worldMatrix is the world matrix of the particle system
  52720. * @param positionToUpdate is the position vector to update with the result
  52721. * @param particle is the particle we are computed the position for
  52722. */
  52723. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52724. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52725. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52726. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52727. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52728. var randY = randRadius * Math.cos(theta);
  52729. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52730. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52731. };
  52732. /**
  52733. * Clones the current emitter and returns a copy of it
  52734. * @returns the new emitter
  52735. */
  52736. SphereParticleEmitter.prototype.clone = function () {
  52737. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52738. BABYLON.Tools.DeepCopy(this, newOne);
  52739. return newOne;
  52740. };
  52741. /**
  52742. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52743. * @param effect defines the update shader
  52744. */
  52745. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52746. effect.setFloat("radius", this.radius);
  52747. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52748. };
  52749. /**
  52750. * Returns a string to use to update the GPU particles update shader
  52751. * @returns a string containng the defines string
  52752. */
  52753. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52754. return "#define SPHEREEMITTER";
  52755. };
  52756. /**
  52757. * Returns the string "SphereParticleEmitter"
  52758. * @returns a string containing the class name
  52759. */
  52760. SphereParticleEmitter.prototype.getClassName = function () {
  52761. return "SphereParticleEmitter";
  52762. };
  52763. /**
  52764. * Serializes the particle system to a JSON object.
  52765. * @returns the JSON object
  52766. */
  52767. SphereParticleEmitter.prototype.serialize = function () {
  52768. var serializationObject = {};
  52769. serializationObject.type = this.getClassName();
  52770. serializationObject.radius = this.radius;
  52771. serializationObject.directionRandomizer = this.directionRandomizer;
  52772. return serializationObject;
  52773. };
  52774. /**
  52775. * Parse properties from a JSON object
  52776. * @param serializationObject defines the JSON object
  52777. */
  52778. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52779. this.radius = serializationObject.radius;
  52780. this.directionRandomizer = serializationObject.directionRandomizer;
  52781. };
  52782. return SphereParticleEmitter;
  52783. }());
  52784. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52785. /**
  52786. * Particle emitter emitting particles from the inside of a sphere.
  52787. * It emits the particles randomly between two vectors.
  52788. */
  52789. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52790. __extends(SphereDirectedParticleEmitter, _super);
  52791. /**
  52792. * Creates a new instance of @see SphereDirectedParticleEmitter
  52793. * @param radius the radius of the emission sphere (1 by default)
  52794. * @param direction1 the min limit of the emission direction (up vector by default)
  52795. * @param direction2 the max limit of the emission direction (up vector by default)
  52796. */
  52797. function SphereDirectedParticleEmitter(radius,
  52798. /**
  52799. * The min limit of the emission direction.
  52800. */
  52801. direction1,
  52802. /**
  52803. * The max limit of the emission direction.
  52804. */
  52805. direction2) {
  52806. if (radius === void 0) { radius = 1; }
  52807. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52808. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52809. var _this = _super.call(this, radius) || this;
  52810. _this.direction1 = direction1;
  52811. _this.direction2 = direction2;
  52812. return _this;
  52813. }
  52814. /**
  52815. * Called by the particle System when the direction is computed for the created particle.
  52816. * @param emitPower is the power of the particle (speed)
  52817. * @param worldMatrix is the world matrix of the particle system
  52818. * @param directionToUpdate is the direction vector to update with the result
  52819. * @param particle is the particle we are computed the direction for
  52820. */
  52821. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52822. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52823. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52824. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52825. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52826. };
  52827. /**
  52828. * Clones the current emitter and returns a copy of it
  52829. * @returns the new emitter
  52830. */
  52831. SphereDirectedParticleEmitter.prototype.clone = function () {
  52832. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52833. BABYLON.Tools.DeepCopy(this, newOne);
  52834. return newOne;
  52835. };
  52836. /**
  52837. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52838. * @param effect defines the update shader
  52839. */
  52840. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52841. effect.setFloat("radius", this.radius);
  52842. effect.setVector3("direction1", this.direction1);
  52843. effect.setVector3("direction2", this.direction2);
  52844. };
  52845. /**
  52846. * Returns a string to use to update the GPU particles update shader
  52847. * @returns a string containng the defines string
  52848. */
  52849. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52850. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52851. };
  52852. /**
  52853. * Returns the string "SphereDirectedParticleEmitter"
  52854. * @returns a string containing the class name
  52855. */
  52856. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52857. return "SphereDirectedParticleEmitter";
  52858. };
  52859. /**
  52860. * Serializes the particle system to a JSON object.
  52861. * @returns the JSON object
  52862. */
  52863. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52864. var serializationObject = _super.prototype.serialize.call(this);
  52865. ;
  52866. serializationObject.direction1 = this.direction1.asArray();
  52867. ;
  52868. serializationObject.direction2 = this.direction2.asArray();
  52869. ;
  52870. return serializationObject;
  52871. };
  52872. /**
  52873. * Parse properties from a JSON object
  52874. * @param serializationObject defines the JSON object
  52875. */
  52876. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52877. _super.prototype.parse.call(this, serializationObject);
  52878. this.direction1.copyFrom(serializationObject.direction1);
  52879. this.direction2.copyFrom(serializationObject.direction2);
  52880. };
  52881. return SphereDirectedParticleEmitter;
  52882. }(SphereParticleEmitter));
  52883. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52884. })(BABYLON || (BABYLON = {}));
  52885. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52886. "use strict";
  52887. var BABYLON;
  52888. (function (BABYLON) {
  52889. /**
  52890. * Represents one particle of a solid particle system.
  52891. * @see SolidParticleSystem
  52892. */
  52893. var SolidParticle = /** @class */ (function () {
  52894. /**
  52895. * Creates a Solid Particle object.
  52896. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52897. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52898. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52899. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52900. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52901. * @param shapeId (integer) is the model shape identifier in the SPS.
  52902. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52903. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52904. */
  52905. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52906. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52907. /**
  52908. * particle global index
  52909. */
  52910. this.idx = 0;
  52911. /**
  52912. * The color of the particle
  52913. */
  52914. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52915. /**
  52916. * The world space position of the particle.
  52917. */
  52918. this.position = BABYLON.Vector3.Zero();
  52919. /**
  52920. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52921. */
  52922. this.rotation = BABYLON.Vector3.Zero();
  52923. /**
  52924. * The scaling of the particle.
  52925. */
  52926. this.scaling = BABYLON.Vector3.One();
  52927. /**
  52928. * The uvs of the particle.
  52929. */
  52930. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52931. /**
  52932. * The current speed of the particle.
  52933. */
  52934. this.velocity = BABYLON.Vector3.Zero();
  52935. /**
  52936. * The pivot point in the particle local space.
  52937. */
  52938. this.pivot = BABYLON.Vector3.Zero();
  52939. /**
  52940. * Must the particle be translated from its pivot point in its local space ?
  52941. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52942. * Default : false
  52943. */
  52944. this.translateFromPivot = false;
  52945. /**
  52946. * Is the particle active or not ?
  52947. */
  52948. this.alive = true;
  52949. /**
  52950. * Is the particle visible or not ?
  52951. */
  52952. this.isVisible = true;
  52953. /**
  52954. * Index of this particle in the global "positions" array (Internal use)
  52955. */
  52956. this._pos = 0;
  52957. /**
  52958. * Index of this particle in the global "indices" array (Internal use)
  52959. */
  52960. this._ind = 0;
  52961. /**
  52962. * ModelShape id of this particle
  52963. */
  52964. this.shapeId = 0;
  52965. /**
  52966. * Index of the particle in its shape id (Internal use)
  52967. */
  52968. this.idxInShape = 0;
  52969. /**
  52970. * Still set as invisible in order to skip useless computations (Internal use)
  52971. */
  52972. this._stillInvisible = false;
  52973. /**
  52974. * Last computed particle rotation matrix
  52975. */
  52976. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52977. /**
  52978. * Parent particle Id, if any.
  52979. * Default null.
  52980. */
  52981. this.parentId = null;
  52982. /**
  52983. * Internal global position in the SPS.
  52984. */
  52985. this._globalPosition = BABYLON.Vector3.Zero();
  52986. this.idx = particleIndex;
  52987. this._pos = positionIndex;
  52988. this._ind = indiceIndex;
  52989. this._model = model;
  52990. this.shapeId = shapeId;
  52991. this.idxInShape = idxInShape;
  52992. this._sps = sps;
  52993. if (modelBoundingInfo) {
  52994. this._modelBoundingInfo = modelBoundingInfo;
  52995. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52996. }
  52997. }
  52998. Object.defineProperty(SolidParticle.prototype, "scale", {
  52999. /**
  53000. * Legacy support, changed scale to scaling
  53001. */
  53002. get: function () {
  53003. return this.scaling;
  53004. },
  53005. /**
  53006. * Legacy support, changed scale to scaling
  53007. */
  53008. set: function (scale) {
  53009. this.scaling = scale;
  53010. },
  53011. enumerable: true,
  53012. configurable: true
  53013. });
  53014. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53015. /**
  53016. * Legacy support, changed quaternion to rotationQuaternion
  53017. */
  53018. get: function () {
  53019. return this.rotationQuaternion;
  53020. },
  53021. /**
  53022. * Legacy support, changed quaternion to rotationQuaternion
  53023. */
  53024. set: function (q) {
  53025. this.rotationQuaternion = q;
  53026. },
  53027. enumerable: true,
  53028. configurable: true
  53029. });
  53030. /**
  53031. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53032. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53033. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53034. * @returns true if it intersects
  53035. */
  53036. SolidParticle.prototype.intersectsMesh = function (target) {
  53037. if (!this._boundingInfo || !target._boundingInfo) {
  53038. return false;
  53039. }
  53040. if (this._sps._bSphereOnly) {
  53041. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53042. }
  53043. return this._boundingInfo.intersects(target._boundingInfo, false);
  53044. };
  53045. return SolidParticle;
  53046. }());
  53047. BABYLON.SolidParticle = SolidParticle;
  53048. /**
  53049. * Represents the shape of the model used by one particle of a solid particle system.
  53050. * SPS internal tool, don't use it manually.
  53051. * @see SolidParticleSystem
  53052. */
  53053. var ModelShape = /** @class */ (function () {
  53054. /**
  53055. * 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.
  53056. * SPS internal tool, don't use it manually.
  53057. * @ignore
  53058. */
  53059. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53060. /**
  53061. * length of the shape in the model indices array (internal use)
  53062. */
  53063. this._indicesLength = 0;
  53064. this.shapeID = id;
  53065. this._shape = shape;
  53066. this._indicesLength = indicesLength;
  53067. this._shapeUV = shapeUV;
  53068. this._positionFunction = posFunction;
  53069. this._vertexFunction = vtxFunction;
  53070. }
  53071. return ModelShape;
  53072. }());
  53073. BABYLON.ModelShape = ModelShape;
  53074. /**
  53075. * Represents a Depth Sorted Particle in the solid particle system.
  53076. * @see SolidParticleSystem
  53077. */
  53078. var DepthSortedParticle = /** @class */ (function () {
  53079. function DepthSortedParticle() {
  53080. /**
  53081. * Index of the particle in the "indices" array
  53082. */
  53083. this.ind = 0;
  53084. /**
  53085. * Length of the particle shape in the "indices" array
  53086. */
  53087. this.indicesLength = 0;
  53088. /**
  53089. * Squared distance from the particle to the camera
  53090. */
  53091. this.sqDistance = 0.0;
  53092. }
  53093. return DepthSortedParticle;
  53094. }());
  53095. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53096. })(BABYLON || (BABYLON = {}));
  53097. //# sourceMappingURL=babylon.solidParticle.js.map
  53098. "use strict";
  53099. var BABYLON;
  53100. (function (BABYLON) {
  53101. /**
  53102. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53103. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  53104. * The SPS is also a particle system. It provides some methods to manage the particles.
  53105. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53106. *
  53107. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53108. */
  53109. var SolidParticleSystem = /** @class */ (function () {
  53110. /**
  53111. * Creates a SPS (Solid Particle System) object.
  53112. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53113. * @param scene (Scene) is the scene in which the SPS is added.
  53114. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53115. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53116. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53117. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53118. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53119. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53120. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53121. */
  53122. function SolidParticleSystem(name, scene, options) {
  53123. /**
  53124. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53125. * Example : var p = SPS.particles[i];
  53126. */
  53127. this.particles = new Array();
  53128. /**
  53129. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53130. */
  53131. this.nbParticles = 0;
  53132. /**
  53133. * If the particles must ever face the camera (default false). Useful for planar particles.
  53134. */
  53135. this.billboard = false;
  53136. /**
  53137. * Recompute normals when adding a shape
  53138. */
  53139. this.recomputeNormals = true;
  53140. /**
  53141. * This a counter ofr your own usage. It's not set by any SPS functions.
  53142. */
  53143. this.counter = 0;
  53144. /**
  53145. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53146. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53147. */
  53148. this.vars = {};
  53149. /**
  53150. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53151. */
  53152. this._bSphereOnly = false;
  53153. /**
  53154. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53155. */
  53156. this._bSphereRadiusFactor = 1.0;
  53157. this._positions = new Array();
  53158. this._indices = new Array();
  53159. this._normals = new Array();
  53160. this._colors = new Array();
  53161. this._uvs = new Array();
  53162. this._index = 0; // indices index
  53163. this._updatable = true;
  53164. this._pickable = false;
  53165. this._isVisibilityBoxLocked = false;
  53166. this._alwaysVisible = false;
  53167. this._depthSort = false;
  53168. this._shapeCounter = 0;
  53169. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53170. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53171. this._computeParticleColor = true;
  53172. this._computeParticleTexture = true;
  53173. this._computeParticleRotation = true;
  53174. this._computeParticleVertex = false;
  53175. this._computeBoundingBox = false;
  53176. this._depthSortParticles = true;
  53177. this._cam_axisZ = BABYLON.Vector3.Zero();
  53178. this._cam_axisY = BABYLON.Vector3.Zero();
  53179. this._cam_axisX = BABYLON.Vector3.Zero();
  53180. this._axisZ = BABYLON.Axis.Z;
  53181. this._camDir = BABYLON.Vector3.Zero();
  53182. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53183. this._rotMatrix = new BABYLON.Matrix();
  53184. this._invertMatrix = new BABYLON.Matrix();
  53185. this._rotated = BABYLON.Vector3.Zero();
  53186. this._quaternion = new BABYLON.Quaternion();
  53187. this._vertex = BABYLON.Vector3.Zero();
  53188. this._normal = BABYLON.Vector3.Zero();
  53189. this._yaw = 0.0;
  53190. this._pitch = 0.0;
  53191. this._roll = 0.0;
  53192. this._halfroll = 0.0;
  53193. this._halfpitch = 0.0;
  53194. this._halfyaw = 0.0;
  53195. this._sinRoll = 0.0;
  53196. this._cosRoll = 0.0;
  53197. this._sinPitch = 0.0;
  53198. this._cosPitch = 0.0;
  53199. this._sinYaw = 0.0;
  53200. this._cosYaw = 0.0;
  53201. this._mustUnrotateFixedNormals = false;
  53202. this._minimum = BABYLON.Vector3.Zero();
  53203. this._maximum = BABYLON.Vector3.Zero();
  53204. this._minBbox = BABYLON.Vector3.Zero();
  53205. this._maxBbox = BABYLON.Vector3.Zero();
  53206. this._particlesIntersect = false;
  53207. this._depthSortFunction = function (p1, p2) {
  53208. return (p2.sqDistance - p1.sqDistance);
  53209. };
  53210. this._needs32Bits = false;
  53211. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53212. this._scaledPivot = BABYLON.Vector3.Zero();
  53213. this._particleHasParent = false;
  53214. this.name = name;
  53215. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53216. this._camera = scene.activeCamera;
  53217. this._pickable = options ? options.isPickable : false;
  53218. this._depthSort = options ? options.enableDepthSort : false;
  53219. this._particlesIntersect = options ? options.particleIntersection : false;
  53220. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53221. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53222. if (options && options.updatable) {
  53223. this._updatable = options.updatable;
  53224. }
  53225. else {
  53226. this._updatable = true;
  53227. }
  53228. if (this._pickable) {
  53229. this.pickedParticles = [];
  53230. }
  53231. if (this._depthSort) {
  53232. this.depthSortedParticles = [];
  53233. }
  53234. }
  53235. /**
  53236. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53237. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53238. * @returns the created mesh
  53239. */
  53240. SolidParticleSystem.prototype.buildMesh = function () {
  53241. if (this.nbParticles === 0) {
  53242. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53243. this.addShape(triangle, 1);
  53244. triangle.dispose();
  53245. }
  53246. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53247. this._positions32 = new Float32Array(this._positions);
  53248. this._uvs32 = new Float32Array(this._uvs);
  53249. this._colors32 = new Float32Array(this._colors);
  53250. if (this.recomputeNormals) {
  53251. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53252. }
  53253. this._normals32 = new Float32Array(this._normals);
  53254. this._fixedNormal32 = new Float32Array(this._normals);
  53255. if (this._mustUnrotateFixedNormals) {
  53256. this._unrotateFixedNormals();
  53257. }
  53258. var vertexData = new BABYLON.VertexData();
  53259. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53260. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53261. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53262. if (this._uvs32) {
  53263. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53264. ;
  53265. }
  53266. if (this._colors32) {
  53267. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53268. }
  53269. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53270. vertexData.applyToMesh(mesh, this._updatable);
  53271. this.mesh = mesh;
  53272. this.mesh.isPickable = this._pickable;
  53273. // free memory
  53274. if (!this._depthSort) {
  53275. this._indices = null;
  53276. }
  53277. this._positions = null;
  53278. this._normals = null;
  53279. this._uvs = null;
  53280. this._colors = null;
  53281. if (!this._updatable) {
  53282. this.particles.length = 0;
  53283. }
  53284. return mesh;
  53285. };
  53286. /**
  53287. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53288. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53289. * Thus the particles generated from `digest()` have their property `position` set yet.
  53290. * @param mesh ( Mesh ) is the mesh to be digested
  53291. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  53292. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53293. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53294. * @returns the current SPS
  53295. */
  53296. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53297. var size = (options && options.facetNb) || 1;
  53298. var number = (options && options.number) || 0;
  53299. var delta = (options && options.delta) || 0;
  53300. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53301. var meshInd = mesh.getIndices();
  53302. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53303. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53304. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53305. var f = 0; // facet counter
  53306. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  53307. // compute size from number
  53308. if (number) {
  53309. number = (number > totalFacets) ? totalFacets : number;
  53310. size = Math.round(totalFacets / number);
  53311. delta = 0;
  53312. }
  53313. else {
  53314. size = (size > totalFacets) ? totalFacets : size;
  53315. }
  53316. var facetPos = []; // submesh positions
  53317. var facetInd = []; // submesh indices
  53318. var facetUV = []; // submesh UV
  53319. var facetCol = []; // submesh colors
  53320. var barycenter = BABYLON.Vector3.Zero();
  53321. var sizeO = size;
  53322. while (f < totalFacets) {
  53323. size = sizeO + Math.floor((1 + delta) * Math.random());
  53324. if (f > totalFacets - size) {
  53325. size = totalFacets - f;
  53326. }
  53327. // reset temp arrays
  53328. facetPos.length = 0;
  53329. facetInd.length = 0;
  53330. facetUV.length = 0;
  53331. facetCol.length = 0;
  53332. // iterate over "size" facets
  53333. var fi = 0;
  53334. for (var j = f * 3; j < (f + size) * 3; j++) {
  53335. facetInd.push(fi);
  53336. var i = meshInd[j];
  53337. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  53338. if (meshUV) {
  53339. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  53340. }
  53341. if (meshCol) {
  53342. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  53343. }
  53344. fi++;
  53345. }
  53346. // create a model shape for each single particle
  53347. var idx = this.nbParticles;
  53348. var shape = this._posToShape(facetPos);
  53349. var shapeUV = this._uvsToShapeUV(facetUV);
  53350. // compute the barycenter of the shape
  53351. var v;
  53352. for (v = 0; v < shape.length; v++) {
  53353. barycenter.addInPlace(shape[v]);
  53354. }
  53355. barycenter.scaleInPlace(1 / shape.length);
  53356. // shift the shape from its barycenter to the origin
  53357. for (v = 0; v < shape.length; v++) {
  53358. shape[v].subtractInPlace(barycenter);
  53359. }
  53360. var bInfo;
  53361. if (this._particlesIntersect) {
  53362. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  53363. }
  53364. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  53365. // add the particle in the SPS
  53366. var currentPos = this._positions.length;
  53367. var currentInd = this._indices.length;
  53368. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  53369. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  53370. // initialize the particle position
  53371. this.particles[this.nbParticles].position.addInPlace(barycenter);
  53372. this._index += shape.length;
  53373. idx++;
  53374. this.nbParticles++;
  53375. this._shapeCounter++;
  53376. f += size;
  53377. }
  53378. return this;
  53379. };
  53380. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  53381. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  53382. var index = 0;
  53383. var idx = 0;
  53384. for (var p = 0; p < this.particles.length; p++) {
  53385. this._particle = this.particles[p];
  53386. this._shape = this._particle._model._shape;
  53387. if (this._particle.rotationQuaternion) {
  53388. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53389. }
  53390. else {
  53391. this._yaw = this._particle.rotation.y;
  53392. this._pitch = this._particle.rotation.x;
  53393. this._roll = this._particle.rotation.z;
  53394. this._quaternionRotationYPR();
  53395. }
  53396. this._quaternionToRotationMatrix();
  53397. this._rotMatrix.invertToRef(this._invertMatrix);
  53398. for (var pt = 0; pt < this._shape.length; pt++) {
  53399. idx = index + pt * 3;
  53400. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  53401. this._fixedNormal32[idx] = this._normal.x;
  53402. this._fixedNormal32[idx + 1] = this._normal.y;
  53403. this._fixedNormal32[idx + 2] = this._normal.z;
  53404. }
  53405. index = idx + 3;
  53406. }
  53407. };
  53408. //reset copy
  53409. SolidParticleSystem.prototype._resetCopy = function () {
  53410. this._copy.position.x = 0;
  53411. this._copy.position.y = 0;
  53412. this._copy.position.z = 0;
  53413. this._copy.rotation.x = 0;
  53414. this._copy.rotation.y = 0;
  53415. this._copy.rotation.z = 0;
  53416. this._copy.rotationQuaternion = null;
  53417. this._copy.scaling.x = 1.0;
  53418. this._copy.scaling.y = 1.0;
  53419. this._copy.scaling.z = 1.0;
  53420. this._copy.uvs.x = 0;
  53421. this._copy.uvs.y = 0;
  53422. this._copy.uvs.z = 1.0;
  53423. this._copy.uvs.w = 1.0;
  53424. this._copy.color = null;
  53425. this._copy.translateFromPivot = false;
  53426. };
  53427. // _meshBuilder : inserts the shape model in the global SPS mesh
  53428. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  53429. var i;
  53430. var u = 0;
  53431. var c = 0;
  53432. var n = 0;
  53433. this._resetCopy();
  53434. if (options && options.positionFunction) {
  53435. options.positionFunction(this._copy, idx, idxInShape);
  53436. this._mustUnrotateFixedNormals = true;
  53437. }
  53438. if (this._copy.rotationQuaternion) {
  53439. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53440. }
  53441. else {
  53442. this._yaw = this._copy.rotation.y;
  53443. this._pitch = this._copy.rotation.x;
  53444. this._roll = this._copy.rotation.z;
  53445. this._quaternionRotationYPR();
  53446. }
  53447. this._quaternionToRotationMatrix();
  53448. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  53449. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  53450. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  53451. if (this._copy.translateFromPivot) {
  53452. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53453. }
  53454. else {
  53455. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53456. }
  53457. for (i = 0; i < shape.length; i++) {
  53458. this._vertex.x = shape[i].x;
  53459. this._vertex.y = shape[i].y;
  53460. this._vertex.z = shape[i].z;
  53461. if (options && options.vertexFunction) {
  53462. options.vertexFunction(this._copy, this._vertex, i);
  53463. }
  53464. this._vertex.x *= this._copy.scaling.x;
  53465. this._vertex.y *= this._copy.scaling.y;
  53466. this._vertex.z *= this._copy.scaling.z;
  53467. this._vertex.x -= this._scaledPivot.x;
  53468. this._vertex.y -= this._scaledPivot.y;
  53469. this._vertex.z -= this._scaledPivot.z;
  53470. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53471. this._rotated.addInPlace(this._pivotBackTranslation);
  53472. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  53473. if (meshUV) {
  53474. 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);
  53475. u += 2;
  53476. }
  53477. if (this._copy.color) {
  53478. this._color = this._copy.color;
  53479. }
  53480. else if (meshCol && meshCol[c] !== undefined) {
  53481. this._color.r = meshCol[c];
  53482. this._color.g = meshCol[c + 1];
  53483. this._color.b = meshCol[c + 2];
  53484. this._color.a = meshCol[c + 3];
  53485. }
  53486. else {
  53487. this._color.r = 1.0;
  53488. this._color.g = 1.0;
  53489. this._color.b = 1.0;
  53490. this._color.a = 1.0;
  53491. }
  53492. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  53493. c += 4;
  53494. if (!this.recomputeNormals && meshNor) {
  53495. this._normal.x = meshNor[n];
  53496. this._normal.y = meshNor[n + 1];
  53497. this._normal.z = meshNor[n + 2];
  53498. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  53499. normals.push(this._normal.x, this._normal.y, this._normal.z);
  53500. n += 3;
  53501. }
  53502. }
  53503. for (i = 0; i < meshInd.length; i++) {
  53504. var current_ind = p + meshInd[i];
  53505. indices.push(current_ind);
  53506. if (current_ind > 65535) {
  53507. this._needs32Bits = true;
  53508. }
  53509. }
  53510. if (this._pickable) {
  53511. var nbfaces = meshInd.length / 3;
  53512. for (i = 0; i < nbfaces; i++) {
  53513. this.pickedParticles.push({ idx: idx, faceId: i });
  53514. }
  53515. }
  53516. if (this._depthSort) {
  53517. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  53518. }
  53519. return this._copy;
  53520. };
  53521. // returns a shape array from positions array
  53522. SolidParticleSystem.prototype._posToShape = function (positions) {
  53523. var shape = [];
  53524. for (var i = 0; i < positions.length; i += 3) {
  53525. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  53526. }
  53527. return shape;
  53528. };
  53529. // returns a shapeUV array from a Vector4 uvs
  53530. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  53531. var shapeUV = [];
  53532. if (uvs) {
  53533. for (var i = 0; i < uvs.length; i++)
  53534. shapeUV.push(uvs[i]);
  53535. }
  53536. return shapeUV;
  53537. };
  53538. // adds a new particle object in the particles array
  53539. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  53540. if (bInfo === void 0) { bInfo = null; }
  53541. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  53542. this.particles.push(sp);
  53543. return sp;
  53544. };
  53545. /**
  53546. * Adds some particles to the SPS from the model shape. Returns the shape id.
  53547. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  53548. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  53549. * @param nb (positive integer) the number of particles to be created from this model
  53550. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  53551. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  53552. * @returns the number of shapes in the system
  53553. */
  53554. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  53555. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53556. var meshInd = mesh.getIndices();
  53557. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53558. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  53559. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53560. var bbInfo;
  53561. if (this._particlesIntersect) {
  53562. bbInfo = mesh.getBoundingInfo();
  53563. }
  53564. var shape = this._posToShape(meshPos);
  53565. var shapeUV = this._uvsToShapeUV(meshUV);
  53566. var posfunc = options ? options.positionFunction : null;
  53567. var vtxfunc = options ? options.vertexFunction : null;
  53568. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  53569. // particles
  53570. var sp;
  53571. var currentCopy;
  53572. var idx = this.nbParticles;
  53573. for (var i = 0; i < nb; i++) {
  53574. var currentPos = this._positions.length;
  53575. var currentInd = this._indices.length;
  53576. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  53577. if (this._updatable) {
  53578. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  53579. sp.position.copyFrom(currentCopy.position);
  53580. sp.rotation.copyFrom(currentCopy.rotation);
  53581. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  53582. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  53583. }
  53584. if (currentCopy.color && sp.color) {
  53585. sp.color.copyFrom(currentCopy.color);
  53586. }
  53587. sp.scaling.copyFrom(currentCopy.scaling);
  53588. sp.uvs.copyFrom(currentCopy.uvs);
  53589. }
  53590. this._index += shape.length;
  53591. idx++;
  53592. }
  53593. this.nbParticles += nb;
  53594. this._shapeCounter++;
  53595. return this._shapeCounter - 1;
  53596. };
  53597. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  53598. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  53599. this._resetCopy();
  53600. if (particle._model._positionFunction) {
  53601. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  53602. }
  53603. if (this._copy.rotationQuaternion) {
  53604. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  53605. }
  53606. else {
  53607. this._yaw = this._copy.rotation.y;
  53608. this._pitch = this._copy.rotation.x;
  53609. this._roll = this._copy.rotation.z;
  53610. this._quaternionRotationYPR();
  53611. }
  53612. this._quaternionToRotationMatrix();
  53613. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53614. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53615. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53616. if (this._copy.translateFromPivot) {
  53617. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  53618. }
  53619. else {
  53620. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  53621. }
  53622. this._shape = particle._model._shape;
  53623. for (var pt = 0; pt < this._shape.length; pt++) {
  53624. this._vertex.x = this._shape[pt].x;
  53625. this._vertex.y = this._shape[pt].y;
  53626. this._vertex.z = this._shape[pt].z;
  53627. if (particle._model._vertexFunction) {
  53628. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  53629. }
  53630. this._vertex.x *= this._copy.scaling.x;
  53631. this._vertex.y *= this._copy.scaling.y;
  53632. this._vertex.z *= this._copy.scaling.z;
  53633. this._vertex.x -= this._scaledPivot.x;
  53634. this._vertex.y -= this._scaledPivot.y;
  53635. this._vertex.z -= this._scaledPivot.z;
  53636. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  53637. this._rotated.addInPlace(this._pivotBackTranslation);
  53638. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  53639. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  53640. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  53641. }
  53642. particle.position.x = 0.0;
  53643. particle.position.y = 0.0;
  53644. particle.position.z = 0.0;
  53645. particle.rotation.x = 0.0;
  53646. particle.rotation.y = 0.0;
  53647. particle.rotation.z = 0.0;
  53648. particle.rotationQuaternion = null;
  53649. particle.scaling.x = 1.0;
  53650. particle.scaling.y = 1.0;
  53651. particle.scaling.z = 1.0;
  53652. particle.uvs.x = 0.0;
  53653. particle.uvs.y = 0.0;
  53654. particle.uvs.z = 1.0;
  53655. particle.uvs.w = 1.0;
  53656. particle.pivot.x = 0.0;
  53657. particle.pivot.y = 0.0;
  53658. particle.pivot.z = 0.0;
  53659. particle.translateFromPivot = false;
  53660. particle.parentId = null;
  53661. };
  53662. /**
  53663. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  53664. * @returns the SPS.
  53665. */
  53666. SolidParticleSystem.prototype.rebuildMesh = function () {
  53667. for (var p = 0; p < this.particles.length; p++) {
  53668. this._rebuildParticle(this.particles[p]);
  53669. }
  53670. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53671. return this;
  53672. };
  53673. /**
  53674. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  53675. * This method calls `updateParticle()` for each particle of the SPS.
  53676. * For an animated SPS, it is usually called within the render loop.
  53677. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  53678. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  53679. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  53680. * @returns the SPS.
  53681. */
  53682. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  53683. if (start === void 0) { start = 0; }
  53684. if (end === void 0) { end = this.nbParticles - 1; }
  53685. if (update === void 0) { update = true; }
  53686. if (!this._updatable) {
  53687. return this;
  53688. }
  53689. // custom beforeUpdate
  53690. this.beforeUpdateParticles(start, end, update);
  53691. this._cam_axisX.x = 1.0;
  53692. this._cam_axisX.y = 0.0;
  53693. this._cam_axisX.z = 0.0;
  53694. this._cam_axisY.x = 0.0;
  53695. this._cam_axisY.y = 1.0;
  53696. this._cam_axisY.z = 0.0;
  53697. this._cam_axisZ.x = 0.0;
  53698. this._cam_axisZ.y = 0.0;
  53699. this._cam_axisZ.z = 1.0;
  53700. // cases when the World Matrix is to be computed first
  53701. if (this.billboard || this._depthSort) {
  53702. this.mesh.computeWorldMatrix(true);
  53703. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53704. }
  53705. // if the particles will always face the camera
  53706. if (this.billboard) {
  53707. // compute the camera position and un-rotate it by the current mesh rotation
  53708. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53709. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53710. this._cam_axisZ.normalize();
  53711. // same for camera up vector extracted from the cam view matrix
  53712. var view = this._camera.getViewMatrix(true);
  53713. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53714. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53715. this._cam_axisY.normalize();
  53716. this._cam_axisX.normalize();
  53717. }
  53718. // if depthSort, compute the camera global position in the mesh local system
  53719. if (this._depthSort) {
  53720. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53721. }
  53722. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53723. var idx = 0; // current position index in the global array positions32
  53724. var index = 0; // position start index in the global array positions32 of the current particle
  53725. var colidx = 0; // current color index in the global array colors32
  53726. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53727. var uvidx = 0; // current uv index in the global array uvs32
  53728. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53729. var pt = 0; // current index in the particle model shape
  53730. if (this.mesh.isFacetDataEnabled) {
  53731. this._computeBoundingBox = true;
  53732. }
  53733. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53734. if (this._computeBoundingBox) {
  53735. if (start == 0 && end == this.nbParticles - 1) {
  53736. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53737. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53738. }
  53739. else {
  53740. if (this.mesh._boundingInfo) {
  53741. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53742. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53743. }
  53744. }
  53745. }
  53746. // particle loop
  53747. index = this.particles[start]._pos;
  53748. var vpos = (index / 3) | 0;
  53749. colorIndex = vpos * 4;
  53750. uvIndex = vpos * 2;
  53751. for (var p = start; p <= end; p++) {
  53752. this._particle = this.particles[p];
  53753. this._shape = this._particle._model._shape;
  53754. this._shapeUV = this._particle._model._shapeUV;
  53755. // call to custom user function to update the particle properties
  53756. this.updateParticle(this._particle);
  53757. // camera-particle distance for depth sorting
  53758. if (this._depthSort && this._depthSortParticles) {
  53759. var dsp = this.depthSortedParticles[p];
  53760. dsp.ind = this._particle._ind;
  53761. dsp.indicesLength = this._particle._model._indicesLength;
  53762. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53763. }
  53764. // skip the computations for inactive or already invisible particles
  53765. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53766. // increment indexes for the next particle
  53767. pt = this._shape.length;
  53768. index += pt * 3;
  53769. colorIndex += pt * 4;
  53770. uvIndex += pt * 2;
  53771. continue;
  53772. }
  53773. if (this._particle.isVisible) {
  53774. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53775. this._particleHasParent = (this._particle.parentId !== null);
  53776. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53777. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53778. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53779. // particle rotation matrix
  53780. if (this.billboard) {
  53781. this._particle.rotation.x = 0.0;
  53782. this._particle.rotation.y = 0.0;
  53783. }
  53784. if (this._computeParticleRotation || this.billboard) {
  53785. if (this._particle.rotationQuaternion) {
  53786. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53787. }
  53788. else {
  53789. this._yaw = this._particle.rotation.y;
  53790. this._pitch = this._particle.rotation.x;
  53791. this._roll = this._particle.rotation.z;
  53792. this._quaternionRotationYPR();
  53793. }
  53794. this._quaternionToRotationMatrix();
  53795. }
  53796. if (this._particleHasParent) {
  53797. this._parent = this.particles[this._particle.parentId];
  53798. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  53799. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  53800. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  53801. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53802. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53803. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53804. if (this._computeParticleRotation || this.billboard) {
  53805. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  53806. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  53807. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  53808. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  53809. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  53810. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  53811. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  53812. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  53813. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  53814. }
  53815. }
  53816. else {
  53817. this._particle._globalPosition.x = this._particle.position.x;
  53818. this._particle._globalPosition.y = this._particle.position.y;
  53819. this._particle._globalPosition.z = this._particle.position.z;
  53820. if (this._computeParticleRotation || this.billboard) {
  53821. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53822. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53823. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53824. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53825. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53826. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53827. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53828. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53829. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53830. }
  53831. }
  53832. if (this._particle.translateFromPivot) {
  53833. this._pivotBackTranslation.x = 0.0;
  53834. this._pivotBackTranslation.y = 0.0;
  53835. this._pivotBackTranslation.z = 0.0;
  53836. }
  53837. else {
  53838. this._pivotBackTranslation.x = this._scaledPivot.x;
  53839. this._pivotBackTranslation.y = this._scaledPivot.y;
  53840. this._pivotBackTranslation.z = this._scaledPivot.z;
  53841. }
  53842. // particle vertex loop
  53843. for (pt = 0; pt < this._shape.length; pt++) {
  53844. idx = index + pt * 3;
  53845. colidx = colorIndex + pt * 4;
  53846. uvidx = uvIndex + pt * 2;
  53847. this._vertex.x = this._shape[pt].x;
  53848. this._vertex.y = this._shape[pt].y;
  53849. this._vertex.z = this._shape[pt].z;
  53850. if (this._computeParticleVertex) {
  53851. this.updateParticleVertex(this._particle, this._vertex, pt);
  53852. }
  53853. // positions
  53854. this._vertex.x *= this._particle.scaling.x;
  53855. this._vertex.y *= this._particle.scaling.y;
  53856. this._vertex.z *= this._particle.scaling.z;
  53857. this._vertex.x -= this._scaledPivot.x;
  53858. this._vertex.y -= this._scaledPivot.y;
  53859. this._vertex.z -= this._scaledPivot.z;
  53860. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53861. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53862. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53863. this._rotated.x += this._pivotBackTranslation.x;
  53864. this._rotated.y += this._pivotBackTranslation.y;
  53865. this._rotated.z += this._pivotBackTranslation.z;
  53866. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53867. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  53868. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  53869. if (this._computeBoundingBox) {
  53870. if (this._positions32[idx] < this._minimum.x) {
  53871. this._minimum.x = this._positions32[idx];
  53872. }
  53873. if (this._positions32[idx] > this._maximum.x) {
  53874. this._maximum.x = this._positions32[idx];
  53875. }
  53876. if (this._positions32[idx + 1] < this._minimum.y) {
  53877. this._minimum.y = this._positions32[idx + 1];
  53878. }
  53879. if (this._positions32[idx + 1] > this._maximum.y) {
  53880. this._maximum.y = this._positions32[idx + 1];
  53881. }
  53882. if (this._positions32[idx + 2] < this._minimum.z) {
  53883. this._minimum.z = this._positions32[idx + 2];
  53884. }
  53885. if (this._positions32[idx + 2] > this._maximum.z) {
  53886. this._maximum.z = this._positions32[idx + 2];
  53887. }
  53888. }
  53889. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53890. if (!this._computeParticleVertex) {
  53891. this._normal.x = this._fixedNormal32[idx];
  53892. this._normal.y = this._fixedNormal32[idx + 1];
  53893. this._normal.z = this._fixedNormal32[idx + 2];
  53894. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53895. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53896. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53897. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53898. 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;
  53899. 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;
  53900. }
  53901. if (this._computeParticleColor && this._particle.color) {
  53902. this._colors32[colidx] = this._particle.color.r;
  53903. this._colors32[colidx + 1] = this._particle.color.g;
  53904. this._colors32[colidx + 2] = this._particle.color.b;
  53905. this._colors32[colidx + 3] = this._particle.color.a;
  53906. }
  53907. if (this._computeParticleTexture) {
  53908. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53909. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53910. }
  53911. }
  53912. }
  53913. else {
  53914. this._particle._stillInvisible = true; // mark the particle as invisible
  53915. for (pt = 0; pt < this._shape.length; pt++) {
  53916. idx = index + pt * 3;
  53917. colidx = colorIndex + pt * 4;
  53918. uvidx = uvIndex + pt * 2;
  53919. this._positions32[idx] = 0.0;
  53920. this._positions32[idx + 1] = 0.0;
  53921. this._positions32[idx + 2] = 0.0;
  53922. this._normals32[idx] = 0.0;
  53923. this._normals32[idx + 1] = 0.0;
  53924. this._normals32[idx + 2] = 0.0;
  53925. if (this._computeParticleColor && this._particle.color) {
  53926. this._colors32[colidx] = this._particle.color.r;
  53927. this._colors32[colidx + 1] = this._particle.color.g;
  53928. this._colors32[colidx + 2] = this._particle.color.b;
  53929. this._colors32[colidx + 3] = this._particle.color.a;
  53930. }
  53931. if (this._computeParticleTexture) {
  53932. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53933. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53934. }
  53935. }
  53936. }
  53937. // if the particle intersections must be computed : update the bbInfo
  53938. if (this._particlesIntersect) {
  53939. var bInfo = this._particle._boundingInfo;
  53940. var bBox = bInfo.boundingBox;
  53941. var bSphere = bInfo.boundingSphere;
  53942. if (!this._bSphereOnly) {
  53943. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53944. for (var b = 0; b < bBox.vectors.length; b++) {
  53945. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53946. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53947. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53948. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53949. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53950. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53951. 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;
  53952. 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;
  53953. 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;
  53954. }
  53955. bBox._update(this.mesh._worldMatrix);
  53956. }
  53957. // place and scale the particle bouding sphere in the SPS local system, then update it
  53958. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53959. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53960. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53961. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53962. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53963. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53964. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53965. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53966. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53967. 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));
  53968. bSphere._update(this.mesh._worldMatrix);
  53969. }
  53970. // increment indexes for the next particle
  53971. index = idx + 3;
  53972. colorIndex = colidx + 4;
  53973. uvIndex = uvidx + 2;
  53974. }
  53975. // if the VBO must be updated
  53976. if (update) {
  53977. if (this._computeParticleColor) {
  53978. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53979. }
  53980. if (this._computeParticleTexture) {
  53981. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53982. }
  53983. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53984. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53985. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53986. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53987. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53988. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53989. for (var i = 0; i < this._normals32.length; i++) {
  53990. this._fixedNormal32[i] = this._normals32[i];
  53991. }
  53992. }
  53993. if (!this.mesh.areNormalsFrozen) {
  53994. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53995. }
  53996. }
  53997. if (this._depthSort && this._depthSortParticles) {
  53998. this.depthSortedParticles.sort(this._depthSortFunction);
  53999. var dspl = this.depthSortedParticles.length;
  54000. var sorted = 0;
  54001. var lind = 0;
  54002. var sind = 0;
  54003. var sid = 0;
  54004. for (sorted = 0; sorted < dspl; sorted++) {
  54005. lind = this.depthSortedParticles[sorted].indicesLength;
  54006. sind = this.depthSortedParticles[sorted].ind;
  54007. for (var i = 0; i < lind; i++) {
  54008. this._indices32[sid] = this._indices[sind + i];
  54009. sid++;
  54010. }
  54011. }
  54012. this.mesh.updateIndices(this._indices32);
  54013. }
  54014. }
  54015. if (this._computeBoundingBox) {
  54016. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54017. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54018. }
  54019. this.afterUpdateParticles(start, end, update);
  54020. return this;
  54021. };
  54022. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54023. this._halfroll = this._roll * 0.5;
  54024. this._halfpitch = this._pitch * 0.5;
  54025. this._halfyaw = this._yaw * 0.5;
  54026. this._sinRoll = Math.sin(this._halfroll);
  54027. this._cosRoll = Math.cos(this._halfroll);
  54028. this._sinPitch = Math.sin(this._halfpitch);
  54029. this._cosPitch = Math.cos(this._halfpitch);
  54030. this._sinYaw = Math.sin(this._halfyaw);
  54031. this._cosYaw = Math.cos(this._halfyaw);
  54032. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54033. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54034. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54035. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54036. };
  54037. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54038. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54039. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54040. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54041. this._rotMatrix.m[3] = 0;
  54042. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54043. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54044. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54045. this._rotMatrix.m[7] = 0;
  54046. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54047. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54048. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54049. this._rotMatrix.m[11] = 0;
  54050. this._rotMatrix.m[12] = 0;
  54051. this._rotMatrix.m[13] = 0;
  54052. this._rotMatrix.m[14] = 0;
  54053. this._rotMatrix.m[15] = 1.0;
  54054. };
  54055. /**
  54056. * Disposes the SPS.
  54057. */
  54058. SolidParticleSystem.prototype.dispose = function () {
  54059. this.mesh.dispose();
  54060. this.vars = null;
  54061. // drop references to internal big arrays for the GC
  54062. this._positions = null;
  54063. this._indices = null;
  54064. this._normals = null;
  54065. this._uvs = null;
  54066. this._colors = null;
  54067. this._indices32 = null;
  54068. this._positions32 = null;
  54069. this._normals32 = null;
  54070. this._fixedNormal32 = null;
  54071. this._uvs32 = null;
  54072. this._colors32 = null;
  54073. this.pickedParticles = null;
  54074. };
  54075. /**
  54076. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54077. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54078. * @returns the SPS.
  54079. */
  54080. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54081. if (!this._isVisibilityBoxLocked) {
  54082. this.mesh.refreshBoundingInfo();
  54083. }
  54084. return this;
  54085. };
  54086. /**
  54087. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54088. * @param size the size (float) of the visibility box
  54089. * note : this doesn't lock the SPS mesh bounding box.
  54090. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54091. */
  54092. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54093. var vis = size / 2;
  54094. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54095. };
  54096. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54097. /**
  54098. * Gets whether the SPS as always visible or not
  54099. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54100. */
  54101. get: function () {
  54102. return this._alwaysVisible;
  54103. },
  54104. /**
  54105. * Sets the SPS as always visible or not
  54106. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54107. */
  54108. set: function (val) {
  54109. this._alwaysVisible = val;
  54110. this.mesh.alwaysSelectAsActiveMesh = val;
  54111. },
  54112. enumerable: true,
  54113. configurable: true
  54114. });
  54115. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54116. /**
  54117. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54118. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54119. */
  54120. get: function () {
  54121. return this._isVisibilityBoxLocked;
  54122. },
  54123. /**
  54124. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54125. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54126. */
  54127. set: function (val) {
  54128. this._isVisibilityBoxLocked = val;
  54129. var boundingInfo = this.mesh.getBoundingInfo();
  54130. boundingInfo.isLocked = val;
  54131. },
  54132. enumerable: true,
  54133. configurable: true
  54134. });
  54135. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54136. /**
  54137. * Gets if `setParticles()` computes the particle rotations or not.
  54138. * Default value : true. The SPS is faster when it's set to false.
  54139. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54140. */
  54141. get: function () {
  54142. return this._computeParticleRotation;
  54143. },
  54144. /**
  54145. * Tells to `setParticles()` to compute the particle rotations or not.
  54146. * Default value : true. The SPS is faster when it's set to false.
  54147. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54148. */
  54149. set: function (val) {
  54150. this._computeParticleRotation = val;
  54151. },
  54152. enumerable: true,
  54153. configurable: true
  54154. });
  54155. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54156. /**
  54157. * Gets if `setParticles()` computes the particle colors or not.
  54158. * Default value : true. The SPS is faster when it's set to false.
  54159. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54160. */
  54161. get: function () {
  54162. return this._computeParticleColor;
  54163. },
  54164. /**
  54165. * Tells to `setParticles()` to compute the particle colors or not.
  54166. * Default value : true. The SPS is faster when it's set to false.
  54167. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54168. */
  54169. set: function (val) {
  54170. this._computeParticleColor = val;
  54171. },
  54172. enumerable: true,
  54173. configurable: true
  54174. });
  54175. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54176. /**
  54177. * Gets if `setParticles()` computes the particle textures or not.
  54178. * Default value : true. The SPS is faster when it's set to false.
  54179. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54180. */
  54181. get: function () {
  54182. return this._computeParticleTexture;
  54183. },
  54184. set: function (val) {
  54185. this._computeParticleTexture = val;
  54186. },
  54187. enumerable: true,
  54188. configurable: true
  54189. });
  54190. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54191. /**
  54192. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54193. * Default value : false. The SPS is faster when it's set to false.
  54194. * Note : the particle custom vertex positions aren't stored values.
  54195. */
  54196. get: function () {
  54197. return this._computeParticleVertex;
  54198. },
  54199. /**
  54200. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54201. * Default value : false. The SPS is faster when it's set to false.
  54202. * Note : the particle custom vertex positions aren't stored values.
  54203. */
  54204. set: function (val) {
  54205. this._computeParticleVertex = val;
  54206. },
  54207. enumerable: true,
  54208. configurable: true
  54209. });
  54210. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54211. /**
  54212. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54213. */
  54214. get: function () {
  54215. return this._computeBoundingBox;
  54216. },
  54217. /**
  54218. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54219. */
  54220. set: function (val) {
  54221. this._computeBoundingBox = val;
  54222. },
  54223. enumerable: true,
  54224. configurable: true
  54225. });
  54226. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54227. /**
  54228. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54229. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54230. * Default : `true`
  54231. */
  54232. get: function () {
  54233. return this._depthSortParticles;
  54234. },
  54235. /**
  54236. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54237. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54238. * Default : `true`
  54239. */
  54240. set: function (val) {
  54241. this._depthSortParticles = val;
  54242. },
  54243. enumerable: true,
  54244. configurable: true
  54245. });
  54246. // =======================================================================
  54247. // Particle behavior logic
  54248. // these following methods may be overwritten by the user to fit his needs
  54249. /**
  54250. * This function does nothing. It may be overwritten to set all the particle first values.
  54251. * The SPS doesn't call this function, you may have to call it by your own.
  54252. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54253. */
  54254. SolidParticleSystem.prototype.initParticles = function () {
  54255. };
  54256. /**
  54257. * This function does nothing. It may be overwritten to recycle a particle.
  54258. * The SPS doesn't call this function, you may have to call it by your own.
  54259. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54260. * @param particle The particle to recycle
  54261. * @returns the recycled particle
  54262. */
  54263. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54264. return particle;
  54265. };
  54266. /**
  54267. * Updates a particle : this function should be overwritten by the user.
  54268. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54269. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54270. * @example : just set a particle position or velocity and recycle conditions
  54271. * @param particle The particle to update
  54272. * @returns the updated particle
  54273. */
  54274. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54275. return particle;
  54276. };
  54277. /**
  54278. * Updates a vertex of a particle : it can be overwritten by the user.
  54279. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54280. * @param particle the current particle
  54281. * @param vertex the current index of the current particle
  54282. * @param pt the index of the current vertex in the particle shape
  54283. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54284. * @example : just set a vertex particle position
  54285. * @returns the updated vertex
  54286. */
  54287. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54288. return vertex;
  54289. };
  54290. /**
  54291. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54292. * This does nothing and may be overwritten by the user.
  54293. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54294. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54295. * @param update the boolean update value actually passed to setParticles()
  54296. */
  54297. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54298. };
  54299. /**
  54300. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  54301. * This will be passed three parameters.
  54302. * This does nothing and may be overwritten by the user.
  54303. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54304. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54305. * @param update the boolean update value actually passed to setParticles()
  54306. */
  54307. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  54308. };
  54309. return SolidParticleSystem;
  54310. }());
  54311. BABYLON.SolidParticleSystem = SolidParticleSystem;
  54312. })(BABYLON || (BABYLON = {}));
  54313. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  54314. "use strict";
  54315. var BABYLON;
  54316. (function (BABYLON) {
  54317. var ShaderMaterial = /** @class */ (function (_super) {
  54318. __extends(ShaderMaterial, _super);
  54319. function ShaderMaterial(name, scene, shaderPath, options) {
  54320. var _this = _super.call(this, name, scene) || this;
  54321. _this._textures = {};
  54322. _this._textureArrays = {};
  54323. _this._floats = {};
  54324. _this._ints = {};
  54325. _this._floatsArrays = {};
  54326. _this._colors3 = {};
  54327. _this._colors3Arrays = {};
  54328. _this._colors4 = {};
  54329. _this._vectors2 = {};
  54330. _this._vectors3 = {};
  54331. _this._vectors4 = {};
  54332. _this._matrices = {};
  54333. _this._matrices3x3 = {};
  54334. _this._matrices2x2 = {};
  54335. _this._vectors2Arrays = {};
  54336. _this._vectors3Arrays = {};
  54337. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  54338. _this._shaderPath = shaderPath;
  54339. options.needAlphaBlending = options.needAlphaBlending || false;
  54340. options.needAlphaTesting = options.needAlphaTesting || false;
  54341. options.attributes = options.attributes || ["position", "normal", "uv"];
  54342. options.uniforms = options.uniforms || ["worldViewProjection"];
  54343. options.uniformBuffers = options.uniformBuffers || [];
  54344. options.samplers = options.samplers || [];
  54345. options.defines = options.defines || [];
  54346. _this._options = options;
  54347. return _this;
  54348. }
  54349. ShaderMaterial.prototype.getClassName = function () {
  54350. return "ShaderMaterial";
  54351. };
  54352. ShaderMaterial.prototype.needAlphaBlending = function () {
  54353. return this._options.needAlphaBlending;
  54354. };
  54355. ShaderMaterial.prototype.needAlphaTesting = function () {
  54356. return this._options.needAlphaTesting;
  54357. };
  54358. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  54359. if (this._options.uniforms.indexOf(uniformName) === -1) {
  54360. this._options.uniforms.push(uniformName);
  54361. }
  54362. };
  54363. ShaderMaterial.prototype.setTexture = function (name, texture) {
  54364. if (this._options.samplers.indexOf(name) === -1) {
  54365. this._options.samplers.push(name);
  54366. }
  54367. this._textures[name] = texture;
  54368. return this;
  54369. };
  54370. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  54371. if (this._options.samplers.indexOf(name) === -1) {
  54372. this._options.samplers.push(name);
  54373. }
  54374. this._checkUniform(name);
  54375. this._textureArrays[name] = textures;
  54376. return this;
  54377. };
  54378. ShaderMaterial.prototype.setFloat = function (name, value) {
  54379. this._checkUniform(name);
  54380. this._floats[name] = value;
  54381. return this;
  54382. };
  54383. ShaderMaterial.prototype.setInt = function (name, value) {
  54384. this._checkUniform(name);
  54385. this._ints[name] = value;
  54386. return this;
  54387. };
  54388. ShaderMaterial.prototype.setFloats = function (name, value) {
  54389. this._checkUniform(name);
  54390. this._floatsArrays[name] = value;
  54391. return this;
  54392. };
  54393. ShaderMaterial.prototype.setColor3 = function (name, value) {
  54394. this._checkUniform(name);
  54395. this._colors3[name] = value;
  54396. return this;
  54397. };
  54398. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  54399. this._checkUniform(name);
  54400. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  54401. color.toArray(arr, arr.length);
  54402. return arr;
  54403. }, []);
  54404. return this;
  54405. };
  54406. ShaderMaterial.prototype.setColor4 = function (name, value) {
  54407. this._checkUniform(name);
  54408. this._colors4[name] = value;
  54409. return this;
  54410. };
  54411. ShaderMaterial.prototype.setVector2 = function (name, value) {
  54412. this._checkUniform(name);
  54413. this._vectors2[name] = value;
  54414. return this;
  54415. };
  54416. ShaderMaterial.prototype.setVector3 = function (name, value) {
  54417. this._checkUniform(name);
  54418. this._vectors3[name] = value;
  54419. return this;
  54420. };
  54421. ShaderMaterial.prototype.setVector4 = function (name, value) {
  54422. this._checkUniform(name);
  54423. this._vectors4[name] = value;
  54424. return this;
  54425. };
  54426. ShaderMaterial.prototype.setMatrix = function (name, value) {
  54427. this._checkUniform(name);
  54428. this._matrices[name] = value;
  54429. return this;
  54430. };
  54431. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  54432. this._checkUniform(name);
  54433. this._matrices3x3[name] = value;
  54434. return this;
  54435. };
  54436. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  54437. this._checkUniform(name);
  54438. this._matrices2x2[name] = value;
  54439. return this;
  54440. };
  54441. ShaderMaterial.prototype.setArray2 = function (name, value) {
  54442. this._checkUniform(name);
  54443. this._vectors2Arrays[name] = value;
  54444. return this;
  54445. };
  54446. ShaderMaterial.prototype.setArray3 = function (name, value) {
  54447. this._checkUniform(name);
  54448. this._vectors3Arrays[name] = value;
  54449. return this;
  54450. };
  54451. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54452. if (!mesh) {
  54453. return true;
  54454. }
  54455. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  54456. return false;
  54457. }
  54458. return false;
  54459. };
  54460. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  54461. var scene = this.getScene();
  54462. var engine = scene.getEngine();
  54463. if (!this.checkReadyOnEveryCall) {
  54464. if (this._renderId === scene.getRenderId()) {
  54465. if (this._checkCache(scene, mesh, useInstances)) {
  54466. return true;
  54467. }
  54468. }
  54469. }
  54470. // Instances
  54471. var defines = [];
  54472. var attribs = [];
  54473. var fallbacks = new BABYLON.EffectFallbacks();
  54474. if (useInstances) {
  54475. defines.push("#define INSTANCES");
  54476. }
  54477. for (var index = 0; index < this._options.defines.length; index++) {
  54478. defines.push(this._options.defines[index]);
  54479. }
  54480. for (var index = 0; index < this._options.attributes.length; index++) {
  54481. attribs.push(this._options.attributes[index]);
  54482. }
  54483. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54484. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54485. defines.push("#define VERTEXCOLOR");
  54486. }
  54487. // Bones
  54488. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  54489. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54490. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54491. if (mesh.numBoneInfluencers > 4) {
  54492. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54493. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54494. }
  54495. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54496. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54497. fallbacks.addCPUSkinningFallback(0, mesh);
  54498. if (this._options.uniforms.indexOf("mBones") === -1) {
  54499. this._options.uniforms.push("mBones");
  54500. }
  54501. }
  54502. else {
  54503. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54504. }
  54505. // Textures
  54506. for (var name in this._textures) {
  54507. if (!this._textures[name].isReady()) {
  54508. return false;
  54509. }
  54510. }
  54511. // Alpha test
  54512. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  54513. defines.push("#define ALPHATEST");
  54514. }
  54515. var previousEffect = this._effect;
  54516. var join = defines.join("\n");
  54517. this._effect = engine.createEffect(this._shaderPath, {
  54518. attributes: attribs,
  54519. uniformsNames: this._options.uniforms,
  54520. uniformBuffersNames: this._options.uniformBuffers,
  54521. samplers: this._options.samplers,
  54522. defines: join,
  54523. fallbacks: fallbacks,
  54524. onCompiled: this.onCompiled,
  54525. onError: this.onError
  54526. }, engine);
  54527. if (!this._effect.isReady()) {
  54528. return false;
  54529. }
  54530. if (previousEffect !== this._effect) {
  54531. scene.resetCachedMaterial();
  54532. }
  54533. this._renderId = scene.getRenderId();
  54534. return true;
  54535. };
  54536. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54537. var scene = this.getScene();
  54538. if (!this._effect) {
  54539. return;
  54540. }
  54541. if (this._options.uniforms.indexOf("world") !== -1) {
  54542. this._effect.setMatrix("world", world);
  54543. }
  54544. if (this._options.uniforms.indexOf("worldView") !== -1) {
  54545. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  54546. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  54547. }
  54548. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  54549. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  54550. }
  54551. };
  54552. ShaderMaterial.prototype.bind = function (world, mesh) {
  54553. // Std values
  54554. this.bindOnlyWorldMatrix(world);
  54555. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  54556. if (this._options.uniforms.indexOf("view") !== -1) {
  54557. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  54558. }
  54559. if (this._options.uniforms.indexOf("projection") !== -1) {
  54560. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  54561. }
  54562. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  54563. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  54564. }
  54565. // Bones
  54566. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54567. var name;
  54568. // Texture
  54569. for (name in this._textures) {
  54570. this._effect.setTexture(name, this._textures[name]);
  54571. }
  54572. // Texture arrays
  54573. for (name in this._textureArrays) {
  54574. this._effect.setTextureArray(name, this._textureArrays[name]);
  54575. }
  54576. // Int
  54577. for (name in this._ints) {
  54578. this._effect.setInt(name, this._ints[name]);
  54579. }
  54580. // Float
  54581. for (name in this._floats) {
  54582. this._effect.setFloat(name, this._floats[name]);
  54583. }
  54584. // Floats
  54585. for (name in this._floatsArrays) {
  54586. this._effect.setArray(name, this._floatsArrays[name]);
  54587. }
  54588. // Color3
  54589. for (name in this._colors3) {
  54590. this._effect.setColor3(name, this._colors3[name]);
  54591. }
  54592. for (name in this._colors3Arrays) {
  54593. this._effect.setArray3(name, this._colors3Arrays[name]);
  54594. }
  54595. // Color4
  54596. for (name in this._colors4) {
  54597. var color = this._colors4[name];
  54598. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54599. }
  54600. // Vector2
  54601. for (name in this._vectors2) {
  54602. this._effect.setVector2(name, this._vectors2[name]);
  54603. }
  54604. // Vector3
  54605. for (name in this._vectors3) {
  54606. this._effect.setVector3(name, this._vectors3[name]);
  54607. }
  54608. // Vector4
  54609. for (name in this._vectors4) {
  54610. this._effect.setVector4(name, this._vectors4[name]);
  54611. }
  54612. // Matrix
  54613. for (name in this._matrices) {
  54614. this._effect.setMatrix(name, this._matrices[name]);
  54615. }
  54616. // Matrix 3x3
  54617. for (name in this._matrices3x3) {
  54618. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  54619. }
  54620. // Matrix 2x2
  54621. for (name in this._matrices2x2) {
  54622. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  54623. }
  54624. // Vector2Array
  54625. for (name in this._vectors2Arrays) {
  54626. this._effect.setArray2(name, this._vectors2Arrays[name]);
  54627. }
  54628. // Vector3Array
  54629. for (name in this._vectors3Arrays) {
  54630. this._effect.setArray3(name, this._vectors3Arrays[name]);
  54631. }
  54632. }
  54633. this._afterBind(mesh);
  54634. };
  54635. ShaderMaterial.prototype.getActiveTextures = function () {
  54636. var activeTextures = _super.prototype.getActiveTextures.call(this);
  54637. for (var name in this._textures) {
  54638. activeTextures.push(this._textures[name]);
  54639. }
  54640. for (var name in this._textureArrays) {
  54641. var array = this._textureArrays[name];
  54642. for (var index = 0; index < array.length; index++) {
  54643. activeTextures.push(array[index]);
  54644. }
  54645. }
  54646. return activeTextures;
  54647. };
  54648. ShaderMaterial.prototype.hasTexture = function (texture) {
  54649. if (_super.prototype.hasTexture.call(this, texture)) {
  54650. return true;
  54651. }
  54652. for (var name in this._textures) {
  54653. if (this._textures[name] === texture) {
  54654. return true;
  54655. }
  54656. }
  54657. for (var name in this._textureArrays) {
  54658. var array = this._textureArrays[name];
  54659. for (var index = 0; index < array.length; index++) {
  54660. if (array[index] === texture) {
  54661. return true;
  54662. }
  54663. }
  54664. }
  54665. return false;
  54666. };
  54667. ShaderMaterial.prototype.clone = function (name) {
  54668. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  54669. return newShaderMaterial;
  54670. };
  54671. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54672. if (forceDisposeTextures) {
  54673. var name;
  54674. for (name in this._textures) {
  54675. this._textures[name].dispose();
  54676. }
  54677. for (name in this._textureArrays) {
  54678. var array = this._textureArrays[name];
  54679. for (var index = 0; index < array.length; index++) {
  54680. array[index].dispose();
  54681. }
  54682. }
  54683. }
  54684. this._textures = {};
  54685. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54686. };
  54687. ShaderMaterial.prototype.serialize = function () {
  54688. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54689. serializationObject.customType = "BABYLON.ShaderMaterial";
  54690. serializationObject.options = this._options;
  54691. serializationObject.shaderPath = this._shaderPath;
  54692. var name;
  54693. // Texture
  54694. serializationObject.textures = {};
  54695. for (name in this._textures) {
  54696. serializationObject.textures[name] = this._textures[name].serialize();
  54697. }
  54698. // Texture arrays
  54699. serializationObject.textureArrays = {};
  54700. for (name in this._textureArrays) {
  54701. serializationObject.textureArrays[name] = [];
  54702. var array = this._textureArrays[name];
  54703. for (var index = 0; index < array.length; index++) {
  54704. serializationObject.textureArrays[name].push(array[index].serialize());
  54705. }
  54706. }
  54707. // Float
  54708. serializationObject.floats = {};
  54709. for (name in this._floats) {
  54710. serializationObject.floats[name] = this._floats[name];
  54711. }
  54712. // Float s
  54713. serializationObject.FloatArrays = {};
  54714. for (name in this._floatsArrays) {
  54715. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54716. }
  54717. // Color3
  54718. serializationObject.colors3 = {};
  54719. for (name in this._colors3) {
  54720. serializationObject.colors3[name] = this._colors3[name].asArray();
  54721. }
  54722. // Color3 array
  54723. serializationObject.colors3Arrays = {};
  54724. for (name in this._colors3Arrays) {
  54725. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54726. }
  54727. // Color4
  54728. serializationObject.colors4 = {};
  54729. for (name in this._colors4) {
  54730. serializationObject.colors4[name] = this._colors4[name].asArray();
  54731. }
  54732. // Vector2
  54733. serializationObject.vectors2 = {};
  54734. for (name in this._vectors2) {
  54735. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54736. }
  54737. // Vector3
  54738. serializationObject.vectors3 = {};
  54739. for (name in this._vectors3) {
  54740. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54741. }
  54742. // Vector4
  54743. serializationObject.vectors4 = {};
  54744. for (name in this._vectors4) {
  54745. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54746. }
  54747. // Matrix
  54748. serializationObject.matrices = {};
  54749. for (name in this._matrices) {
  54750. serializationObject.matrices[name] = this._matrices[name].asArray();
  54751. }
  54752. // Matrix 3x3
  54753. serializationObject.matrices3x3 = {};
  54754. for (name in this._matrices3x3) {
  54755. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54756. }
  54757. // Matrix 2x2
  54758. serializationObject.matrices2x2 = {};
  54759. for (name in this._matrices2x2) {
  54760. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54761. }
  54762. // Vector2Array
  54763. serializationObject.vectors2Arrays = {};
  54764. for (name in this._vectors2Arrays) {
  54765. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54766. }
  54767. // Vector3Array
  54768. serializationObject.vectors3Arrays = {};
  54769. for (name in this._vectors3Arrays) {
  54770. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54771. }
  54772. return serializationObject;
  54773. };
  54774. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54775. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54776. var name;
  54777. // Texture
  54778. for (name in source.textures) {
  54779. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54780. }
  54781. // Texture arrays
  54782. for (name in source.textureArrays) {
  54783. var array = source.textureArrays[name];
  54784. var textureArray = new Array();
  54785. for (var index = 0; index < array.length; index++) {
  54786. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54787. }
  54788. material.setTextureArray(name, textureArray);
  54789. }
  54790. // Float
  54791. for (name in source.floats) {
  54792. material.setFloat(name, source.floats[name]);
  54793. }
  54794. // Float s
  54795. for (name in source.floatsArrays) {
  54796. material.setFloats(name, source.floatsArrays[name]);
  54797. }
  54798. // Color3
  54799. for (name in source.colors3) {
  54800. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54801. }
  54802. // Color3 arrays
  54803. for (name in source.colors3Arrays) {
  54804. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54805. if (i % 3 === 0) {
  54806. arr.push([num]);
  54807. }
  54808. else {
  54809. arr[arr.length - 1].push(num);
  54810. }
  54811. return arr;
  54812. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54813. material.setColor3Array(name, colors);
  54814. }
  54815. // Color4
  54816. for (name in source.colors4) {
  54817. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54818. }
  54819. // Vector2
  54820. for (name in source.vectors2) {
  54821. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54822. }
  54823. // Vector3
  54824. for (name in source.vectors3) {
  54825. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54826. }
  54827. // Vector4
  54828. for (name in source.vectors4) {
  54829. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54830. }
  54831. // Matrix
  54832. for (name in source.matrices) {
  54833. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54834. }
  54835. // Matrix 3x3
  54836. for (name in source.matrices3x3) {
  54837. material.setMatrix3x3(name, source.matrices3x3[name]);
  54838. }
  54839. // Matrix 2x2
  54840. for (name in source.matrices2x2) {
  54841. material.setMatrix2x2(name, source.matrices2x2[name]);
  54842. }
  54843. // Vector2Array
  54844. for (name in source.vectors2Arrays) {
  54845. material.setArray2(name, source.vectors2Arrays[name]);
  54846. }
  54847. // Vector3Array
  54848. for (name in source.vectors3Arrays) {
  54849. material.setArray3(name, source.vectors3Arrays[name]);
  54850. }
  54851. return material;
  54852. };
  54853. return ShaderMaterial;
  54854. }(BABYLON.Material));
  54855. BABYLON.ShaderMaterial = ShaderMaterial;
  54856. })(BABYLON || (BABYLON = {}));
  54857. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54858. "use strict";
  54859. var BABYLON;
  54860. (function (BABYLON) {
  54861. var GroundMesh = /** @class */ (function (_super) {
  54862. __extends(GroundMesh, _super);
  54863. function GroundMesh(name, scene) {
  54864. var _this = _super.call(this, name, scene) || this;
  54865. _this.generateOctree = false;
  54866. return _this;
  54867. }
  54868. GroundMesh.prototype.getClassName = function () {
  54869. return "GroundMesh";
  54870. };
  54871. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54872. get: function () {
  54873. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54874. },
  54875. enumerable: true,
  54876. configurable: true
  54877. });
  54878. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54879. get: function () {
  54880. return this._subdivisionsX;
  54881. },
  54882. enumerable: true,
  54883. configurable: true
  54884. });
  54885. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54886. get: function () {
  54887. return this._subdivisionsY;
  54888. },
  54889. enumerable: true,
  54890. configurable: true
  54891. });
  54892. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54893. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54894. this._subdivisionsX = chunksCount;
  54895. this._subdivisionsY = chunksCount;
  54896. this.subdivide(chunksCount);
  54897. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54898. };
  54899. /**
  54900. * Returns a height (y) value in the Worl system :
  54901. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54902. * Returns the ground y position if (x, z) are outside the ground surface.
  54903. */
  54904. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54905. var world = this.getWorldMatrix();
  54906. var invMat = BABYLON.Tmp.Matrix[5];
  54907. world.invertToRef(invMat);
  54908. var tmpVect = BABYLON.Tmp.Vector3[8];
  54909. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54910. x = tmpVect.x;
  54911. z = tmpVect.z;
  54912. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54913. return this.position.y;
  54914. }
  54915. if (!this._heightQuads || this._heightQuads.length == 0) {
  54916. this._initHeightQuads();
  54917. this._computeHeightQuads();
  54918. }
  54919. var facet = this._getFacetAt(x, z);
  54920. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54921. // return y in the World system
  54922. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54923. return tmpVect.y;
  54924. };
  54925. /**
  54926. * Returns a normalized vector (Vector3) orthogonal to the ground
  54927. * at the ground coordinates (x, z) expressed in the World system.
  54928. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54929. */
  54930. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54931. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54932. this.getNormalAtCoordinatesToRef(x, z, normal);
  54933. return normal;
  54934. };
  54935. /**
  54936. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54937. * at the ground coordinates (x, z) expressed in the World system.
  54938. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54939. * Returns the GroundMesh.
  54940. */
  54941. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54942. var world = this.getWorldMatrix();
  54943. var tmpMat = BABYLON.Tmp.Matrix[5];
  54944. world.invertToRef(tmpMat);
  54945. var tmpVect = BABYLON.Tmp.Vector3[8];
  54946. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54947. x = tmpVect.x;
  54948. z = tmpVect.z;
  54949. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54950. return this;
  54951. }
  54952. if (!this._heightQuads || this._heightQuads.length == 0) {
  54953. this._initHeightQuads();
  54954. this._computeHeightQuads();
  54955. }
  54956. var facet = this._getFacetAt(x, z);
  54957. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54958. return this;
  54959. };
  54960. /**
  54961. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54962. * if the ground has been updated.
  54963. * This can be used in the render loop.
  54964. * Returns the GroundMesh.
  54965. */
  54966. GroundMesh.prototype.updateCoordinateHeights = function () {
  54967. if (!this._heightQuads || this._heightQuads.length == 0) {
  54968. this._initHeightQuads();
  54969. }
  54970. this._computeHeightQuads();
  54971. return this;
  54972. };
  54973. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54974. GroundMesh.prototype._getFacetAt = function (x, z) {
  54975. // retrieve col and row from x, z coordinates in the ground local system
  54976. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54977. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54978. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54979. var facet;
  54980. if (z < quad.slope.x * x + quad.slope.y) {
  54981. facet = quad.facet1;
  54982. }
  54983. else {
  54984. facet = quad.facet2;
  54985. }
  54986. return facet;
  54987. };
  54988. // Creates and populates the heightMap array with "facet" elements :
  54989. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54990. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54991. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54992. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54993. // Returns the GroundMesh.
  54994. GroundMesh.prototype._initHeightQuads = function () {
  54995. var subdivisionsX = this._subdivisionsX;
  54996. var subdivisionsY = this._subdivisionsY;
  54997. this._heightQuads = new Array();
  54998. for (var row = 0; row < subdivisionsY; row++) {
  54999. for (var col = 0; col < subdivisionsX; col++) {
  55000. 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) };
  55001. this._heightQuads[row * subdivisionsX + col] = quad;
  55002. }
  55003. }
  55004. return this;
  55005. };
  55006. // Compute each quad element values and update the the heightMap array :
  55007. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55008. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55009. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55010. // Returns the GroundMesh.
  55011. GroundMesh.prototype._computeHeightQuads = function () {
  55012. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55013. if (!positions) {
  55014. return this;
  55015. }
  55016. var v1 = BABYLON.Tmp.Vector3[3];
  55017. var v2 = BABYLON.Tmp.Vector3[2];
  55018. var v3 = BABYLON.Tmp.Vector3[1];
  55019. var v4 = BABYLON.Tmp.Vector3[0];
  55020. var v1v2 = BABYLON.Tmp.Vector3[4];
  55021. var v1v3 = BABYLON.Tmp.Vector3[5];
  55022. var v1v4 = BABYLON.Tmp.Vector3[6];
  55023. var norm1 = BABYLON.Tmp.Vector3[7];
  55024. var norm2 = BABYLON.Tmp.Vector3[8];
  55025. var i = 0;
  55026. var j = 0;
  55027. var k = 0;
  55028. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55029. var h = 0;
  55030. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55031. var d2 = 0;
  55032. var subdivisionsX = this._subdivisionsX;
  55033. var subdivisionsY = this._subdivisionsY;
  55034. for (var row = 0; row < subdivisionsY; row++) {
  55035. for (var col = 0; col < subdivisionsX; col++) {
  55036. i = col * 3;
  55037. j = row * (subdivisionsX + 1) * 3;
  55038. k = (row + 1) * (subdivisionsX + 1) * 3;
  55039. v1.x = positions[j + i];
  55040. v1.y = positions[j + i + 1];
  55041. v1.z = positions[j + i + 2];
  55042. v2.x = positions[j + i + 3];
  55043. v2.y = positions[j + i + 4];
  55044. v2.z = positions[j + i + 5];
  55045. v3.x = positions[k + i];
  55046. v3.y = positions[k + i + 1];
  55047. v3.z = positions[k + i + 2];
  55048. v4.x = positions[k + i + 3];
  55049. v4.y = positions[k + i + 4];
  55050. v4.z = positions[k + i + 5];
  55051. // 2D slope V1V4
  55052. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55053. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55054. // facet equations :
  55055. // we compute each facet normal vector
  55056. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55057. // we compute the value d by applying the equation to v1 which belongs to the plane
  55058. // then we store the facet equation in a Vector4
  55059. v2.subtractToRef(v1, v1v2);
  55060. v3.subtractToRef(v1, v1v3);
  55061. v4.subtractToRef(v1, v1v4);
  55062. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55063. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55064. norm1.normalize();
  55065. norm2.normalize();
  55066. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55067. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55068. var quad = this._heightQuads[row * subdivisionsX + col];
  55069. quad.slope.copyFromFloats(cd, h);
  55070. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55071. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55072. }
  55073. }
  55074. return this;
  55075. };
  55076. GroundMesh.prototype.serialize = function (serializationObject) {
  55077. _super.prototype.serialize.call(this, serializationObject);
  55078. serializationObject.subdivisionsX = this._subdivisionsX;
  55079. serializationObject.subdivisionsY = this._subdivisionsY;
  55080. serializationObject.minX = this._minX;
  55081. serializationObject.maxX = this._maxX;
  55082. serializationObject.minZ = this._minZ;
  55083. serializationObject.maxZ = this._maxZ;
  55084. serializationObject.width = this._width;
  55085. serializationObject.height = this._height;
  55086. };
  55087. GroundMesh.Parse = function (parsedMesh, scene) {
  55088. var result = new GroundMesh(parsedMesh.name, scene);
  55089. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55090. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55091. result._minX = parsedMesh.minX;
  55092. result._maxX = parsedMesh.maxX;
  55093. result._minZ = parsedMesh.minZ;
  55094. result._maxZ = parsedMesh.maxZ;
  55095. result._width = parsedMesh.width;
  55096. result._height = parsedMesh.height;
  55097. return result;
  55098. };
  55099. return GroundMesh;
  55100. }(BABYLON.Mesh));
  55101. BABYLON.GroundMesh = GroundMesh;
  55102. })(BABYLON || (BABYLON = {}));
  55103. //# sourceMappingURL=babylon.groundMesh.js.map
  55104. "use strict";
  55105. var BABYLON;
  55106. (function (BABYLON) {
  55107. /**
  55108. * Creates an instance based on a source mesh.
  55109. */
  55110. var InstancedMesh = /** @class */ (function (_super) {
  55111. __extends(InstancedMesh, _super);
  55112. function InstancedMesh(name, source) {
  55113. var _this = _super.call(this, name, source.getScene()) || this;
  55114. source.instances.push(_this);
  55115. _this._sourceMesh = source;
  55116. _this.position.copyFrom(source.position);
  55117. _this.rotation.copyFrom(source.rotation);
  55118. _this.scaling.copyFrom(source.scaling);
  55119. if (source.rotationQuaternion) {
  55120. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55121. }
  55122. _this.infiniteDistance = source.infiniteDistance;
  55123. _this.setPivotMatrix(source.getPivotMatrix());
  55124. _this.refreshBoundingInfo();
  55125. _this._syncSubMeshes();
  55126. return _this;
  55127. }
  55128. /**
  55129. * Returns the string "InstancedMesh".
  55130. */
  55131. InstancedMesh.prototype.getClassName = function () {
  55132. return "InstancedMesh";
  55133. };
  55134. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55135. // Methods
  55136. get: function () {
  55137. return this._sourceMesh.receiveShadows;
  55138. },
  55139. enumerable: true,
  55140. configurable: true
  55141. });
  55142. Object.defineProperty(InstancedMesh.prototype, "material", {
  55143. get: function () {
  55144. return this._sourceMesh.material;
  55145. },
  55146. enumerable: true,
  55147. configurable: true
  55148. });
  55149. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55150. get: function () {
  55151. return this._sourceMesh.visibility;
  55152. },
  55153. enumerable: true,
  55154. configurable: true
  55155. });
  55156. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55157. get: function () {
  55158. return this._sourceMesh.skeleton;
  55159. },
  55160. enumerable: true,
  55161. configurable: true
  55162. });
  55163. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55164. get: function () {
  55165. return this._sourceMesh.renderingGroupId;
  55166. },
  55167. set: function (value) {
  55168. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  55169. return;
  55170. }
  55171. //no-op with warning
  55172. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55173. },
  55174. enumerable: true,
  55175. configurable: true
  55176. });
  55177. /**
  55178. * Returns the total number of vertices (integer).
  55179. */
  55180. InstancedMesh.prototype.getTotalVertices = function () {
  55181. return this._sourceMesh.getTotalVertices();
  55182. };
  55183. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55184. get: function () {
  55185. return this._sourceMesh;
  55186. },
  55187. enumerable: true,
  55188. configurable: true
  55189. });
  55190. /**
  55191. * Is this node ready to be used/rendered
  55192. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55193. * @return {boolean} is it ready
  55194. */
  55195. InstancedMesh.prototype.isReady = function (completeCheck) {
  55196. if (completeCheck === void 0) { completeCheck = false; }
  55197. return this._sourceMesh.isReady(completeCheck, true);
  55198. };
  55199. /**
  55200. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55201. */
  55202. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55203. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55204. };
  55205. /**
  55206. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55207. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55208. * The `data` are either a numeric array either a Float32Array.
  55209. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55210. * 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).
  55211. * Note that a new underlying VertexBuffer object is created each call.
  55212. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55213. *
  55214. * Possible `kind` values :
  55215. * - BABYLON.VertexBuffer.PositionKind
  55216. * - BABYLON.VertexBuffer.UVKind
  55217. * - BABYLON.VertexBuffer.UV2Kind
  55218. * - BABYLON.VertexBuffer.UV3Kind
  55219. * - BABYLON.VertexBuffer.UV4Kind
  55220. * - BABYLON.VertexBuffer.UV5Kind
  55221. * - BABYLON.VertexBuffer.UV6Kind
  55222. * - BABYLON.VertexBuffer.ColorKind
  55223. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55224. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55225. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55226. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55227. *
  55228. * Returns the Mesh.
  55229. */
  55230. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55231. if (this.sourceMesh) {
  55232. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55233. }
  55234. return this.sourceMesh;
  55235. };
  55236. /**
  55237. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55238. * If the mesh has no geometry, it is simply returned as it is.
  55239. * The `data` are either a numeric array either a Float32Array.
  55240. * No new underlying VertexBuffer object is created.
  55241. * 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.
  55242. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55243. *
  55244. * Possible `kind` values :
  55245. * - BABYLON.VertexBuffer.PositionKind
  55246. * - BABYLON.VertexBuffer.UVKind
  55247. * - BABYLON.VertexBuffer.UV2Kind
  55248. * - BABYLON.VertexBuffer.UV3Kind
  55249. * - BABYLON.VertexBuffer.UV4Kind
  55250. * - BABYLON.VertexBuffer.UV5Kind
  55251. * - BABYLON.VertexBuffer.UV6Kind
  55252. * - BABYLON.VertexBuffer.ColorKind
  55253. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55254. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55255. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55256. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55257. *
  55258. * Returns the Mesh.
  55259. */
  55260. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55261. if (this.sourceMesh) {
  55262. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55263. }
  55264. return this.sourceMesh;
  55265. };
  55266. /**
  55267. * Sets the mesh indices.
  55268. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55269. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55270. * This method creates a new index buffer each call.
  55271. * Returns the Mesh.
  55272. */
  55273. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55274. if (totalVertices === void 0) { totalVertices = null; }
  55275. if (this.sourceMesh) {
  55276. this.sourceMesh.setIndices(indices, totalVertices);
  55277. }
  55278. return this.sourceMesh;
  55279. };
  55280. /**
  55281. * Boolean : True if the mesh owns the requested kind of data.
  55282. */
  55283. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55284. return this._sourceMesh.isVerticesDataPresent(kind);
  55285. };
  55286. /**
  55287. * Returns an array of indices (IndicesArray).
  55288. */
  55289. InstancedMesh.prototype.getIndices = function () {
  55290. return this._sourceMesh.getIndices();
  55291. };
  55292. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55293. get: function () {
  55294. return this._sourceMesh._positions;
  55295. },
  55296. enumerable: true,
  55297. configurable: true
  55298. });
  55299. /**
  55300. * Sets a new updated BoundingInfo to the mesh.
  55301. * Returns the mesh.
  55302. */
  55303. InstancedMesh.prototype.refreshBoundingInfo = function () {
  55304. var meshBB = this._sourceMesh.getBoundingInfo();
  55305. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  55306. this._updateBoundingInfo();
  55307. return this;
  55308. };
  55309. InstancedMesh.prototype._preActivate = function () {
  55310. if (this._currentLOD) {
  55311. this._currentLOD._preActivate();
  55312. }
  55313. return this;
  55314. };
  55315. InstancedMesh.prototype._activate = function (renderId) {
  55316. if (this._currentLOD) {
  55317. this._currentLOD._registerInstanceForRenderId(this, renderId);
  55318. }
  55319. return this;
  55320. };
  55321. /**
  55322. * Returns the current associated LOD AbstractMesh.
  55323. */
  55324. InstancedMesh.prototype.getLOD = function (camera) {
  55325. if (!camera) {
  55326. return this;
  55327. }
  55328. var boundingInfo = this.getBoundingInfo();
  55329. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  55330. if (this._currentLOD === this.sourceMesh) {
  55331. return this;
  55332. }
  55333. return this._currentLOD;
  55334. };
  55335. InstancedMesh.prototype._syncSubMeshes = function () {
  55336. this.releaseSubMeshes();
  55337. if (this._sourceMesh.subMeshes) {
  55338. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  55339. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  55340. }
  55341. }
  55342. return this;
  55343. };
  55344. InstancedMesh.prototype._generatePointsArray = function () {
  55345. return this._sourceMesh._generatePointsArray();
  55346. };
  55347. /**
  55348. * Creates a new InstancedMesh from the current mesh.
  55349. * - name (string) : the cloned mesh name
  55350. * - newParent (optional Node) : the optional Node to parent the clone to.
  55351. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  55352. *
  55353. * Returns the clone.
  55354. */
  55355. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55356. var result = this._sourceMesh.createInstance(name);
  55357. // Deep copy
  55358. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  55359. // Bounding info
  55360. this.refreshBoundingInfo();
  55361. // Parent
  55362. if (newParent) {
  55363. result.parent = newParent;
  55364. }
  55365. if (!doNotCloneChildren) {
  55366. // Children
  55367. for (var index = 0; index < this.getScene().meshes.length; index++) {
  55368. var mesh = this.getScene().meshes[index];
  55369. if (mesh.parent === this) {
  55370. mesh.clone(mesh.name, result);
  55371. }
  55372. }
  55373. }
  55374. result.computeWorldMatrix(true);
  55375. return result;
  55376. };
  55377. /**
  55378. * Disposes the InstancedMesh.
  55379. * Returns nothing.
  55380. */
  55381. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  55382. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  55383. // Remove from mesh
  55384. var index = this._sourceMesh.instances.indexOf(this);
  55385. this._sourceMesh.instances.splice(index, 1);
  55386. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  55387. };
  55388. return InstancedMesh;
  55389. }(BABYLON.AbstractMesh));
  55390. BABYLON.InstancedMesh = InstancedMesh;
  55391. })(BABYLON || (BABYLON = {}));
  55392. //# sourceMappingURL=babylon.instancedMesh.js.map
  55393. "use strict";
  55394. var BABYLON;
  55395. (function (BABYLON) {
  55396. var LinesMesh = /** @class */ (function (_super) {
  55397. __extends(LinesMesh, _super);
  55398. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  55399. if (scene === void 0) { scene = null; }
  55400. if (parent === void 0) { parent = null; }
  55401. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  55402. _this.useVertexColor = useVertexColor;
  55403. _this.useVertexAlpha = useVertexAlpha;
  55404. _this.color = new BABYLON.Color3(1, 1, 1);
  55405. _this.alpha = 1;
  55406. if (source) {
  55407. _this.color = source.color.clone();
  55408. _this.alpha = source.alpha;
  55409. _this.useVertexColor = source.useVertexColor;
  55410. _this.useVertexAlpha = source.useVertexAlpha;
  55411. }
  55412. _this._intersectionThreshold = 0.1;
  55413. var defines = [];
  55414. var options = {
  55415. attributes: [BABYLON.VertexBuffer.PositionKind],
  55416. uniforms: ["world", "viewProjection"],
  55417. needAlphaBlending: true,
  55418. defines: defines
  55419. };
  55420. if (useVertexAlpha === false) {
  55421. options.needAlphaBlending = false;
  55422. }
  55423. if (!useVertexColor) {
  55424. options.uniforms.push("color");
  55425. }
  55426. else {
  55427. options.defines.push("#define VERTEXCOLOR");
  55428. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  55429. }
  55430. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  55431. return _this;
  55432. }
  55433. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  55434. /**
  55435. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55436. * This margin is expressed in world space coordinates, so its value may vary.
  55437. * Default value is 0.1
  55438. * @returns the intersection Threshold value.
  55439. */
  55440. get: function () {
  55441. return this._intersectionThreshold;
  55442. },
  55443. /**
  55444. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  55445. * This margin is expressed in world space coordinates, so its value may vary.
  55446. * @param value the new threshold to apply
  55447. */
  55448. set: function (value) {
  55449. if (this._intersectionThreshold === value) {
  55450. return;
  55451. }
  55452. this._intersectionThreshold = value;
  55453. if (this.geometry) {
  55454. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  55455. }
  55456. },
  55457. enumerable: true,
  55458. configurable: true
  55459. });
  55460. /**
  55461. * Returns the string "LineMesh"
  55462. */
  55463. LinesMesh.prototype.getClassName = function () {
  55464. return "LinesMesh";
  55465. };
  55466. Object.defineProperty(LinesMesh.prototype, "material", {
  55467. get: function () {
  55468. return this._colorShader;
  55469. },
  55470. set: function (value) {
  55471. // Do nothing
  55472. },
  55473. enumerable: true,
  55474. configurable: true
  55475. });
  55476. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  55477. get: function () {
  55478. return false;
  55479. },
  55480. enumerable: true,
  55481. configurable: true
  55482. });
  55483. LinesMesh.prototype.createInstance = function (name) {
  55484. throw new Error("LinesMeshes do not support createInstance.");
  55485. };
  55486. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  55487. if (!this._geometry) {
  55488. return this;
  55489. }
  55490. // VBOs
  55491. this._geometry._bind(this._colorShader.getEffect());
  55492. // Color
  55493. if (!this.useVertexColor) {
  55494. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  55495. }
  55496. return this;
  55497. };
  55498. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  55499. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  55500. return this;
  55501. }
  55502. var engine = this.getScene().getEngine();
  55503. // Draw order
  55504. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  55505. return this;
  55506. };
  55507. LinesMesh.prototype.dispose = function (doNotRecurse) {
  55508. this._colorShader.dispose();
  55509. _super.prototype.dispose.call(this, doNotRecurse);
  55510. };
  55511. /**
  55512. * Returns a new LineMesh object cloned from the current one.
  55513. */
  55514. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  55515. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  55516. };
  55517. return LinesMesh;
  55518. }(BABYLON.Mesh));
  55519. BABYLON.LinesMesh = LinesMesh;
  55520. })(BABYLON || (BABYLON = {}));
  55521. //# sourceMappingURL=babylon.linesMesh.js.map
  55522. "use strict";
  55523. var BABYLON;
  55524. (function (BABYLON) {
  55525. var MeshBuilder = /** @class */ (function () {
  55526. function MeshBuilder() {
  55527. }
  55528. MeshBuilder.updateSideOrientation = function (orientation) {
  55529. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  55530. return BABYLON.Mesh.DOUBLESIDE;
  55531. }
  55532. if (orientation === undefined || orientation === null) {
  55533. return BABYLON.Mesh.FRONTSIDE;
  55534. }
  55535. return orientation;
  55536. };
  55537. /**
  55538. * Creates a box mesh.
  55539. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  55540. * The parameter `size` sets the size (float) of each box side (default 1).
  55541. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  55542. * 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).
  55543. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55544. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55545. * 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).
  55546. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55548. */
  55549. MeshBuilder.CreateBox = function (name, options, scene) {
  55550. if (scene === void 0) { scene = null; }
  55551. var box = new BABYLON.Mesh(name, scene);
  55552. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55553. box._originalBuilderSideOrientation = options.sideOrientation;
  55554. var vertexData = BABYLON.VertexData.CreateBox(options);
  55555. vertexData.applyToMesh(box, options.updatable);
  55556. return box;
  55557. };
  55558. /**
  55559. * Creates a sphere mesh.
  55560. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  55561. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  55562. * 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`).
  55563. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  55564. * 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
  55565. * 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).
  55566. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55567. * 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).
  55568. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55569. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55570. */
  55571. MeshBuilder.CreateSphere = function (name, options, scene) {
  55572. var sphere = new BABYLON.Mesh(name, scene);
  55573. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55574. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55575. var vertexData = BABYLON.VertexData.CreateSphere(options);
  55576. vertexData.applyToMesh(sphere, options.updatable);
  55577. return sphere;
  55578. };
  55579. /**
  55580. * Creates a plane polygonal mesh. By default, this is a disc.
  55581. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  55582. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  55583. * 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.
  55584. * 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
  55585. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55586. * 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).
  55587. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55589. */
  55590. MeshBuilder.CreateDisc = function (name, options, scene) {
  55591. if (scene === void 0) { scene = null; }
  55592. var disc = new BABYLON.Mesh(name, scene);
  55593. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55594. disc._originalBuilderSideOrientation = options.sideOrientation;
  55595. var vertexData = BABYLON.VertexData.CreateDisc(options);
  55596. vertexData.applyToMesh(disc, options.updatable);
  55597. return disc;
  55598. };
  55599. /**
  55600. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  55601. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  55602. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  55603. * 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`).
  55604. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  55605. * 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.
  55606. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55607. * 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).
  55608. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55609. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55610. */
  55611. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  55612. var sphere = new BABYLON.Mesh(name, scene);
  55613. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55614. sphere._originalBuilderSideOrientation = options.sideOrientation;
  55615. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  55616. vertexData.applyToMesh(sphere, options.updatable);
  55617. return sphere;
  55618. };
  55619. ;
  55620. /**
  55621. * Creates a ribbon mesh.
  55622. * 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.
  55623. *
  55624. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  55625. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  55626. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  55627. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  55628. * 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.
  55629. * 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.
  55630. * 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
  55631. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55632. * 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).
  55633. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55634. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55635. * 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.
  55636. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  55637. * 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
  55638. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  55639. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  55640. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55641. */
  55642. MeshBuilder.CreateRibbon = function (name, options, scene) {
  55643. if (scene === void 0) { scene = null; }
  55644. var pathArray = options.pathArray;
  55645. var closeArray = options.closeArray;
  55646. var closePath = options.closePath;
  55647. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55648. var instance = options.instance;
  55649. var updatable = options.updatable;
  55650. if (instance) {
  55651. // positionFunction : ribbon case
  55652. // only pathArray and sideOrientation parameters are taken into account for positions update
  55653. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  55654. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  55655. var positionFunction = function (positions) {
  55656. var minlg = pathArray[0].length;
  55657. var i = 0;
  55658. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  55659. for (var si = 1; si <= ns; si++) {
  55660. for (var p = 0; p < pathArray.length; p++) {
  55661. var path = pathArray[p];
  55662. var l = path.length;
  55663. minlg = (minlg < l) ? minlg : l;
  55664. var j = 0;
  55665. while (j < minlg) {
  55666. positions[i] = path[j].x;
  55667. positions[i + 1] = path[j].y;
  55668. positions[i + 2] = path[j].z;
  55669. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  55670. BABYLON.Tmp.Vector3[0].x = path[j].x;
  55671. }
  55672. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  55673. BABYLON.Tmp.Vector3[1].x = path[j].x;
  55674. }
  55675. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  55676. BABYLON.Tmp.Vector3[0].y = path[j].y;
  55677. }
  55678. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  55679. BABYLON.Tmp.Vector3[1].y = path[j].y;
  55680. }
  55681. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  55682. BABYLON.Tmp.Vector3[0].z = path[j].z;
  55683. }
  55684. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  55685. BABYLON.Tmp.Vector3[1].z = path[j].z;
  55686. }
  55687. j++;
  55688. i += 3;
  55689. }
  55690. if (instance._closePath) {
  55691. positions[i] = path[0].x;
  55692. positions[i + 1] = path[0].y;
  55693. positions[i + 2] = path[0].z;
  55694. i += 3;
  55695. }
  55696. }
  55697. }
  55698. };
  55699. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55700. positionFunction(positions);
  55701. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  55702. instance._boundingInfo.update(instance._worldMatrix);
  55703. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55704. if (options.colors) {
  55705. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55706. for (var c = 0; c < options.colors.length; c++) {
  55707. colors[c * 4] = options.colors[c].r;
  55708. colors[c * 4 + 1] = options.colors[c].g;
  55709. colors[c * 4 + 2] = options.colors[c].b;
  55710. colors[c * 4 + 3] = options.colors[c].a;
  55711. }
  55712. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55713. }
  55714. if (options.uvs) {
  55715. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55716. for (var i = 0; i < options.uvs.length; i++) {
  55717. uvs[i * 2] = options.uvs[i].x;
  55718. uvs[i * 2 + 1] = options.uvs[i].y;
  55719. }
  55720. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55721. }
  55722. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55723. var indices = instance.getIndices();
  55724. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55725. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55726. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55727. if (instance._closePath) {
  55728. var indexFirst = 0;
  55729. var indexLast = 0;
  55730. for (var p = 0; p < pathArray.length; p++) {
  55731. indexFirst = instance._idx[p] * 3;
  55732. if (p + 1 < pathArray.length) {
  55733. indexLast = (instance._idx[p + 1] - 1) * 3;
  55734. }
  55735. else {
  55736. indexLast = normals.length - 3;
  55737. }
  55738. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55739. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55740. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55741. normals[indexLast] = normals[indexFirst];
  55742. normals[indexLast + 1] = normals[indexFirst + 1];
  55743. normals[indexLast + 2] = normals[indexFirst + 2];
  55744. }
  55745. }
  55746. if (!(instance.areNormalsFrozen)) {
  55747. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55748. }
  55749. }
  55750. return instance;
  55751. }
  55752. else {
  55753. var ribbon = new BABYLON.Mesh(name, scene);
  55754. ribbon._originalBuilderSideOrientation = sideOrientation;
  55755. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55756. if (closePath) {
  55757. ribbon._idx = vertexData._idx;
  55758. }
  55759. ribbon._closePath = closePath;
  55760. ribbon._closeArray = closeArray;
  55761. vertexData.applyToMesh(ribbon, updatable);
  55762. return ribbon;
  55763. }
  55764. };
  55765. /**
  55766. * Creates a cylinder or a cone mesh.
  55767. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55768. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55769. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55770. * 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.
  55771. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55772. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55773. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55774. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55775. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55776. * 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).
  55777. * 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
  55778. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55779. * 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
  55780. * 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.
  55781. * If `enclose` is false, a ring surface is one element.
  55782. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55783. * 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
  55784. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55785. * 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).
  55786. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55787. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55788. */
  55789. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55790. var cylinder = new BABYLON.Mesh(name, scene);
  55791. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55792. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55793. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55794. vertexData.applyToMesh(cylinder, options.updatable);
  55795. return cylinder;
  55796. };
  55797. /**
  55798. * Creates a torus mesh.
  55799. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55800. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55801. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55802. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55803. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55804. * 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).
  55805. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55806. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55807. */
  55808. MeshBuilder.CreateTorus = function (name, options, scene) {
  55809. var torus = new BABYLON.Mesh(name, scene);
  55810. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55811. torus._originalBuilderSideOrientation = options.sideOrientation;
  55812. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55813. vertexData.applyToMesh(torus, options.updatable);
  55814. return torus;
  55815. };
  55816. /**
  55817. * Creates a torus knot mesh.
  55818. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55819. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55820. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55821. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55822. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55823. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55824. * 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).
  55825. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55826. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55827. */
  55828. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55829. var torusKnot = new BABYLON.Mesh(name, scene);
  55830. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55831. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55832. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55833. vertexData.applyToMesh(torusKnot, options.updatable);
  55834. return torusKnot;
  55835. };
  55836. /**
  55837. * Creates a line system mesh.
  55838. * A line system is a pool of many lines gathered in a single mesh.
  55839. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55840. * 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.
  55841. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55842. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55843. * 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
  55844. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55845. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55846. * 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
  55847. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55848. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55849. */
  55850. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55851. var instance = options.instance;
  55852. var lines = options.lines;
  55853. var colors = options.colors;
  55854. if (instance) {
  55855. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55856. var vertexColor;
  55857. var lineColors;
  55858. if (colors) {
  55859. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55860. }
  55861. var i = 0;
  55862. var c = 0;
  55863. for (var l = 0; l < lines.length; l++) {
  55864. var points = lines[l];
  55865. for (var p = 0; p < points.length; p++) {
  55866. positions[i] = points[p].x;
  55867. positions[i + 1] = points[p].y;
  55868. positions[i + 2] = points[p].z;
  55869. if (colors && vertexColor) {
  55870. lineColors = colors[l];
  55871. vertexColor[c] = lineColors[p].r;
  55872. vertexColor[c + 1] = lineColors[p].g;
  55873. vertexColor[c + 2] = lineColors[p].b;
  55874. vertexColor[c + 3] = lineColors[p].a;
  55875. c += 4;
  55876. }
  55877. i += 3;
  55878. }
  55879. }
  55880. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55881. if (colors && vertexColor) {
  55882. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55883. }
  55884. return instance;
  55885. }
  55886. // line system creation
  55887. var useVertexColor = (colors) ? true : false;
  55888. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55889. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55890. vertexData.applyToMesh(lineSystem, options.updatable);
  55891. return lineSystem;
  55892. };
  55893. /**
  55894. * Creates a line mesh.
  55895. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55896. * 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.
  55897. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55898. * The parameter `points` is an array successive Vector3.
  55899. * 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
  55900. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55901. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55902. * When updating an instance, remember that only point positions can change, not the number of points.
  55903. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55904. */
  55905. MeshBuilder.CreateLines = function (name, options, scene) {
  55906. if (scene === void 0) { scene = null; }
  55907. var colors = (options.colors) ? [options.colors] : null;
  55908. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55909. return lines;
  55910. };
  55911. /**
  55912. * Creates a dashed line mesh.
  55913. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55914. * 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.
  55915. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55916. * The parameter `points` is an array successive Vector3.
  55917. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55918. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55919. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55920. * 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
  55921. * When updating an instance, remember that only point positions can change, not the number of points.
  55922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55923. */
  55924. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55925. if (scene === void 0) { scene = null; }
  55926. var points = options.points;
  55927. var instance = options.instance;
  55928. var gapSize = options.gapSize || 1;
  55929. var dashSize = options.dashSize || 3;
  55930. if (instance) {
  55931. var positionFunction = function (positions) {
  55932. var curvect = BABYLON.Vector3.Zero();
  55933. var nbSeg = positions.length / 6;
  55934. var lg = 0;
  55935. var nb = 0;
  55936. var shft = 0;
  55937. var dashshft = 0;
  55938. var curshft = 0;
  55939. var p = 0;
  55940. var i = 0;
  55941. var j = 0;
  55942. for (i = 0; i < points.length - 1; i++) {
  55943. points[i + 1].subtractToRef(points[i], curvect);
  55944. lg += curvect.length();
  55945. }
  55946. shft = lg / nbSeg;
  55947. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55948. for (i = 0; i < points.length - 1; i++) {
  55949. points[i + 1].subtractToRef(points[i], curvect);
  55950. nb = Math.floor(curvect.length() / shft);
  55951. curvect.normalize();
  55952. j = 0;
  55953. while (j < nb && p < positions.length) {
  55954. curshft = shft * j;
  55955. positions[p] = points[i].x + curshft * curvect.x;
  55956. positions[p + 1] = points[i].y + curshft * curvect.y;
  55957. positions[p + 2] = points[i].z + curshft * curvect.z;
  55958. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55959. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55960. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55961. p += 6;
  55962. j++;
  55963. }
  55964. }
  55965. while (p < positions.length) {
  55966. positions[p] = points[i].x;
  55967. positions[p + 1] = points[i].y;
  55968. positions[p + 2] = points[i].z;
  55969. p += 3;
  55970. }
  55971. };
  55972. instance.updateMeshPositions(positionFunction, false);
  55973. return instance;
  55974. }
  55975. // dashed lines creation
  55976. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55977. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55978. vertexData.applyToMesh(dashedLines, options.updatable);
  55979. dashedLines.dashSize = dashSize;
  55980. dashedLines.gapSize = gapSize;
  55981. return dashedLines;
  55982. };
  55983. /**
  55984. * Creates an extruded shape mesh.
  55985. * 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.
  55986. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55987. *
  55988. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55989. * 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
  55990. * extruded along the Z axis.
  55991. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55992. * 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.
  55993. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55994. * 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
  55995. * 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
  55996. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55997. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55998. * 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).
  55999. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56000. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56002. */
  56003. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56004. if (scene === void 0) { scene = null; }
  56005. var path = options.path;
  56006. var shape = options.shape;
  56007. var scale = options.scale || 1;
  56008. var rotation = options.rotation || 0;
  56009. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56010. var updatable = options.updatable;
  56011. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56012. var instance = options.instance || null;
  56013. var invertUV = options.invertUV || false;
  56014. 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);
  56015. };
  56016. /**
  56017. * Creates an custom extruded shape mesh.
  56018. * 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.
  56019. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56020. *
  56021. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56022. * 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
  56023. * extruded along the Z axis.
  56024. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56025. * 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
  56026. * and the distance of this point from the begining of the path :
  56027. * ```javascript
  56028. * var rotationFunction = function(i, distance) {
  56029. * // do things
  56030. * return rotationValue; }
  56031. * ```
  56032. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56033. * 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
  56034. * and the distance of this point from the begining of the path :
  56035. * ```javascript
  56036. * var scaleFunction = function(i, distance) {
  56037. * // do things
  56038. * return scaleValue;}
  56039. * ```
  56040. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56041. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56042. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56043. * 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
  56044. * 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
  56045. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56046. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56047. * 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).
  56048. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56049. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56050. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56051. */
  56052. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56053. var path = options.path;
  56054. var shape = options.shape;
  56055. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56056. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56057. var ribbonCloseArray = options.ribbonCloseArray || false;
  56058. var ribbonClosePath = options.ribbonClosePath || false;
  56059. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56060. var updatable = options.updatable;
  56061. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56062. var instance = options.instance;
  56063. var invertUV = options.invertUV || false;
  56064. 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);
  56065. };
  56066. /**
  56067. * Creates lathe mesh.
  56068. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56069. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56070. *
  56071. * 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
  56072. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56073. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56074. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56075. * 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.
  56076. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56077. * 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
  56078. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56079. * 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).
  56080. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56081. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56082. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56083. */
  56084. MeshBuilder.CreateLathe = function (name, options, scene) {
  56085. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56086. var closed = (options.closed === undefined) ? true : options.closed;
  56087. var shape = options.shape;
  56088. var radius = options.radius || 1;
  56089. var tessellation = options.tessellation || 64;
  56090. var updatable = options.updatable;
  56091. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56092. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56093. var pi2 = Math.PI * 2;
  56094. var paths = new Array();
  56095. var invertUV = options.invertUV || false;
  56096. var i = 0;
  56097. var p = 0;
  56098. var step = pi2 / tessellation * arc;
  56099. var rotated;
  56100. var path = new Array();
  56101. ;
  56102. for (i = 0; i <= tessellation; i++) {
  56103. var path = [];
  56104. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56105. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56106. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56107. }
  56108. for (p = 0; p < shape.length; p++) {
  56109. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56110. path.push(rotated);
  56111. }
  56112. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56113. 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));
  56114. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56115. }
  56116. paths.push(path);
  56117. }
  56118. // lathe ribbon
  56119. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56120. return lathe;
  56121. };
  56122. /**
  56123. * Creates a plane mesh.
  56124. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56125. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56126. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56127. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56128. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56129. * 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).
  56130. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56131. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56132. */
  56133. MeshBuilder.CreatePlane = function (name, options, scene) {
  56134. var plane = new BABYLON.Mesh(name, scene);
  56135. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56136. plane._originalBuilderSideOrientation = options.sideOrientation;
  56137. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56138. vertexData.applyToMesh(plane, options.updatable);
  56139. if (options.sourcePlane) {
  56140. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56141. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56142. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56143. plane.rotate(vectorProduct, product);
  56144. }
  56145. return plane;
  56146. };
  56147. /**
  56148. * Creates a ground mesh.
  56149. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56150. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56151. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56152. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56153. */
  56154. MeshBuilder.CreateGround = function (name, options, scene) {
  56155. var ground = new BABYLON.GroundMesh(name, scene);
  56156. ground._setReady(false);
  56157. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56158. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56159. ground._width = options.width || 1;
  56160. ground._height = options.height || 1;
  56161. ground._maxX = ground._width / 2;
  56162. ground._maxZ = ground._height / 2;
  56163. ground._minX = -ground._maxX;
  56164. ground._minZ = -ground._maxZ;
  56165. var vertexData = BABYLON.VertexData.CreateGround(options);
  56166. vertexData.applyToMesh(ground, options.updatable);
  56167. ground._setReady(true);
  56168. return ground;
  56169. };
  56170. /**
  56171. * Creates a tiled ground mesh.
  56172. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56173. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56174. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56175. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56176. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56177. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56178. * numbers of subdivisions on the ground width and height of each tile.
  56179. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56180. */
  56181. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56182. var tiledGround = new BABYLON.Mesh(name, scene);
  56183. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56184. vertexData.applyToMesh(tiledGround, options.updatable);
  56185. return tiledGround;
  56186. };
  56187. /**
  56188. * Creates a ground mesh from a height map.
  56189. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56190. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56191. * The parameter `url` sets the URL of the height map image resource.
  56192. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56193. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56194. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56195. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56196. * 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.
  56197. * 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).
  56198. * This function is passed the newly built mesh :
  56199. * ```javascript
  56200. * function(mesh) { // do things
  56201. * return; }
  56202. * ```
  56203. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56204. */
  56205. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56206. var width = options.width || 10.0;
  56207. var height = options.height || 10.0;
  56208. var subdivisions = options.subdivisions || 1 | 0;
  56209. var minHeight = options.minHeight || 0.0;
  56210. var maxHeight = options.maxHeight || 1.0;
  56211. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56212. var updatable = options.updatable;
  56213. var onReady = options.onReady;
  56214. var ground = new BABYLON.GroundMesh(name, scene);
  56215. ground._subdivisionsX = subdivisions;
  56216. ground._subdivisionsY = subdivisions;
  56217. ground._width = width;
  56218. ground._height = height;
  56219. ground._maxX = ground._width / 2.0;
  56220. ground._maxZ = ground._height / 2.0;
  56221. ground._minX = -ground._maxX;
  56222. ground._minZ = -ground._maxZ;
  56223. ground._setReady(false);
  56224. var onload = function (img) {
  56225. // Getting height map data
  56226. var canvas = document.createElement("canvas");
  56227. var context = canvas.getContext("2d");
  56228. if (!context) {
  56229. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56230. }
  56231. if (scene.isDisposed) {
  56232. return;
  56233. }
  56234. var bufferWidth = img.width;
  56235. var bufferHeight = img.height;
  56236. canvas.width = bufferWidth;
  56237. canvas.height = bufferHeight;
  56238. context.drawImage(img, 0, 0);
  56239. // Create VertexData from map data
  56240. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56241. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56242. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56243. width: width, height: height,
  56244. subdivisions: subdivisions,
  56245. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56246. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56247. });
  56248. vertexData.applyToMesh(ground, updatable);
  56249. //execute ready callback, if set
  56250. if (onReady) {
  56251. onReady(ground);
  56252. }
  56253. ground._setReady(true);
  56254. };
  56255. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56256. return ground;
  56257. };
  56258. /**
  56259. * Creates a polygon mesh.
  56260. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56261. * 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.
  56262. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56263. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56264. * 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).
  56265. * Remember you can only change the shape positions, not their number when updating a polygon.
  56266. */
  56267. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56268. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56269. var shape = options.shape;
  56270. var holes = options.holes || [];
  56271. var depth = options.depth || 0;
  56272. var contours = [];
  56273. var hole = [];
  56274. for (var i = 0; i < shape.length; i++) {
  56275. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56276. }
  56277. var epsilon = 0.00000001;
  56278. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56279. contours.pop();
  56280. }
  56281. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56282. for (var hNb = 0; hNb < holes.length; hNb++) {
  56283. hole = [];
  56284. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56285. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56286. }
  56287. polygonTriangulation.addHole(hole);
  56288. }
  56289. var polygon = polygonTriangulation.build(options.updatable, depth);
  56290. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56291. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56292. vertexData.applyToMesh(polygon, options.updatable);
  56293. return polygon;
  56294. };
  56295. ;
  56296. /**
  56297. * Creates an extruded polygon mesh, with depth in the Y direction.
  56298. * 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).
  56299. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56300. */
  56301. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  56302. return MeshBuilder.CreatePolygon(name, options, scene);
  56303. };
  56304. ;
  56305. /**
  56306. * Creates a tube mesh.
  56307. * 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.
  56308. *
  56309. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  56310. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  56311. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  56312. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  56313. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  56314. * 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.
  56315. * It must return a radius value (positive float) :
  56316. * ```javascript
  56317. * var radiusFunction = function(i, distance) {
  56318. * // do things
  56319. * return radius; }
  56320. * ```
  56321. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  56322. * 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
  56323. * 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
  56324. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56325. * 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).
  56326. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56327. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56328. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56329. */
  56330. MeshBuilder.CreateTube = function (name, options, scene) {
  56331. var path = options.path;
  56332. var instance = options.instance;
  56333. var radius = 1.0;
  56334. if (instance) {
  56335. radius = instance.radius;
  56336. }
  56337. if (options.radius !== undefined) {
  56338. radius = options.radius;
  56339. }
  56340. ;
  56341. var tessellation = options.tessellation || 64 | 0;
  56342. var radiusFunction = options.radiusFunction || null;
  56343. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56344. var invertUV = options.invertUV || false;
  56345. var updatable = options.updatable;
  56346. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56347. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  56348. // tube geometry
  56349. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  56350. var tangents = path3D.getTangents();
  56351. var normals = path3D.getNormals();
  56352. var distances = path3D.getDistances();
  56353. var pi2 = Math.PI * 2;
  56354. var step = pi2 / tessellation * arc;
  56355. var returnRadius = function () { return radius; };
  56356. var radiusFunctionFinal = radiusFunction || returnRadius;
  56357. var circlePath;
  56358. var rad;
  56359. var normal;
  56360. var rotated;
  56361. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56362. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56363. for (var i = 0; i < path.length; i++) {
  56364. rad = radiusFunctionFinal(i, distances[i]); // current radius
  56365. circlePath = Array(); // current circle array
  56366. normal = normals[i]; // current normal
  56367. for (var t = 0; t < tessellation; t++) {
  56368. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  56369. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  56370. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  56371. rotated.scaleInPlace(rad).addInPlace(path[i]);
  56372. circlePath[t] = rotated;
  56373. }
  56374. circlePaths[index] = circlePath;
  56375. index++;
  56376. }
  56377. // cap
  56378. var capPath = function (nbPoints, pathIndex) {
  56379. var pointCap = Array();
  56380. for (var i = 0; i < nbPoints; i++) {
  56381. pointCap.push(path[pathIndex]);
  56382. }
  56383. return pointCap;
  56384. };
  56385. switch (cap) {
  56386. case BABYLON.Mesh.NO_CAP:
  56387. break;
  56388. case BABYLON.Mesh.CAP_START:
  56389. circlePaths[0] = capPath(tessellation, 0);
  56390. circlePaths[1] = circlePaths[2].slice(0);
  56391. break;
  56392. case BABYLON.Mesh.CAP_END:
  56393. circlePaths[index] = circlePaths[index - 1].slice(0);
  56394. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56395. break;
  56396. case BABYLON.Mesh.CAP_ALL:
  56397. circlePaths[0] = capPath(tessellation, 0);
  56398. circlePaths[1] = circlePaths[2].slice(0);
  56399. circlePaths[index] = circlePaths[index - 1].slice(0);
  56400. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  56401. break;
  56402. default:
  56403. break;
  56404. }
  56405. return circlePaths;
  56406. };
  56407. var path3D;
  56408. var pathArray;
  56409. if (instance) {
  56410. var arc = options.arc || instance.arc;
  56411. path3D = (instance.path3D).update(path);
  56412. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  56413. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  56414. instance.path3D = path3D;
  56415. instance.pathArray = pathArray;
  56416. instance.arc = arc;
  56417. instance.radius = radius;
  56418. return instance;
  56419. }
  56420. // tube creation
  56421. path3D = new BABYLON.Path3D(path);
  56422. var newPathArray = new Array();
  56423. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56424. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  56425. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56426. tube.pathArray = pathArray;
  56427. tube.path3D = path3D;
  56428. tube.tessellation = tessellation;
  56429. tube.cap = cap;
  56430. tube.arc = options.arc;
  56431. tube.radius = radius;
  56432. return tube;
  56433. };
  56434. /**
  56435. * Creates a polyhedron mesh.
  56436. *
  56437. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  56438. * 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
  56439. * to choose the wanted type.
  56440. * The parameter `size` (positive float, default 1) sets the polygon size.
  56441. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  56442. * 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`.
  56443. * 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
  56444. * 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)`).
  56445. * 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
  56446. * 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.
  56447. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56448. * 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).
  56449. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56451. */
  56452. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  56453. var polyhedron = new BABYLON.Mesh(name, scene);
  56454. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56455. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  56456. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  56457. vertexData.applyToMesh(polyhedron, options.updatable);
  56458. return polyhedron;
  56459. };
  56460. /**
  56461. * Creates a decal mesh.
  56462. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  56463. * 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.
  56464. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  56465. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  56466. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  56467. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  56468. */
  56469. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  56470. var indices = sourceMesh.getIndices();
  56471. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56472. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56473. var position = options.position || BABYLON.Vector3.Zero();
  56474. var normal = options.normal || BABYLON.Vector3.Up();
  56475. var size = options.size || BABYLON.Vector3.One();
  56476. var angle = options.angle || 0;
  56477. // Getting correct rotation
  56478. if (!normal) {
  56479. var target = new BABYLON.Vector3(0, 0, 1);
  56480. var camera = sourceMesh.getScene().activeCamera;
  56481. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  56482. normal = camera.globalPosition.subtract(cameraWorldTarget);
  56483. }
  56484. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  56485. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  56486. var pitch = Math.atan2(normal.y, len);
  56487. // Matrix
  56488. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  56489. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  56490. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  56491. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  56492. var vertexData = new BABYLON.VertexData();
  56493. vertexData.indices = [];
  56494. vertexData.positions = [];
  56495. vertexData.normals = [];
  56496. vertexData.uvs = [];
  56497. var currentVertexDataIndex = 0;
  56498. var extractDecalVector3 = function (indexId) {
  56499. var result = new BABYLON.PositionNormalVertex();
  56500. if (!indices || !positions || !normals) {
  56501. return result;
  56502. }
  56503. var vertexId = indices[indexId];
  56504. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  56505. // Send vector to decal local world
  56506. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  56507. // Get normal
  56508. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  56509. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  56510. return result;
  56511. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  56512. var clip = function (vertices, axis) {
  56513. if (vertices.length === 0) {
  56514. return vertices;
  56515. }
  56516. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  56517. var clipVertices = function (v0, v1) {
  56518. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  56519. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  56520. };
  56521. var result = new Array();
  56522. for (var index = 0; index < vertices.length; index += 3) {
  56523. var v1Out;
  56524. var v2Out;
  56525. var v3Out;
  56526. var total = 0;
  56527. var nV1 = null;
  56528. var nV2 = null;
  56529. var nV3 = null;
  56530. var nV4 = null;
  56531. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  56532. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  56533. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  56534. v1Out = d1 > 0;
  56535. v2Out = d2 > 0;
  56536. v3Out = d3 > 0;
  56537. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  56538. switch (total) {
  56539. case 0:
  56540. result.push(vertices[index]);
  56541. result.push(vertices[index + 1]);
  56542. result.push(vertices[index + 2]);
  56543. break;
  56544. case 1:
  56545. if (v1Out) {
  56546. nV1 = vertices[index + 1];
  56547. nV2 = vertices[index + 2];
  56548. nV3 = clipVertices(vertices[index], nV1);
  56549. nV4 = clipVertices(vertices[index], nV2);
  56550. }
  56551. if (v2Out) {
  56552. nV1 = vertices[index];
  56553. nV2 = vertices[index + 2];
  56554. nV3 = clipVertices(vertices[index + 1], nV1);
  56555. nV4 = clipVertices(vertices[index + 1], nV2);
  56556. result.push(nV3);
  56557. result.push(nV2.clone());
  56558. result.push(nV1.clone());
  56559. result.push(nV2.clone());
  56560. result.push(nV3.clone());
  56561. result.push(nV4);
  56562. break;
  56563. }
  56564. if (v3Out) {
  56565. nV1 = vertices[index];
  56566. nV2 = vertices[index + 1];
  56567. nV3 = clipVertices(vertices[index + 2], nV1);
  56568. nV4 = clipVertices(vertices[index + 2], nV2);
  56569. }
  56570. if (nV1 && nV2 && nV3 && nV4) {
  56571. result.push(nV1.clone());
  56572. result.push(nV2.clone());
  56573. result.push(nV3);
  56574. result.push(nV4);
  56575. result.push(nV3.clone());
  56576. result.push(nV2.clone());
  56577. }
  56578. break;
  56579. case 2:
  56580. if (!v1Out) {
  56581. nV1 = vertices[index].clone();
  56582. nV2 = clipVertices(nV1, vertices[index + 1]);
  56583. nV3 = clipVertices(nV1, vertices[index + 2]);
  56584. result.push(nV1);
  56585. result.push(nV2);
  56586. result.push(nV3);
  56587. }
  56588. if (!v2Out) {
  56589. nV1 = vertices[index + 1].clone();
  56590. nV2 = clipVertices(nV1, vertices[index + 2]);
  56591. nV3 = clipVertices(nV1, vertices[index]);
  56592. result.push(nV1);
  56593. result.push(nV2);
  56594. result.push(nV3);
  56595. }
  56596. if (!v3Out) {
  56597. nV1 = vertices[index + 2].clone();
  56598. nV2 = clipVertices(nV1, vertices[index]);
  56599. nV3 = clipVertices(nV1, vertices[index + 1]);
  56600. result.push(nV1);
  56601. result.push(nV2);
  56602. result.push(nV3);
  56603. }
  56604. break;
  56605. case 3:
  56606. break;
  56607. }
  56608. }
  56609. return result;
  56610. };
  56611. for (var index = 0; index < indices.length; index += 3) {
  56612. var faceVertices = new Array();
  56613. faceVertices.push(extractDecalVector3(index));
  56614. faceVertices.push(extractDecalVector3(index + 1));
  56615. faceVertices.push(extractDecalVector3(index + 2));
  56616. // Clip
  56617. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  56618. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  56619. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  56620. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  56621. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  56622. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  56623. if (faceVertices.length === 0) {
  56624. continue;
  56625. }
  56626. // Add UVs and get back to world
  56627. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  56628. var vertex = faceVertices[vIndex];
  56629. //TODO check for Int32Array | Uint32Array | Uint16Array
  56630. vertexData.indices.push(currentVertexDataIndex);
  56631. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  56632. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  56633. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  56634. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  56635. currentVertexDataIndex++;
  56636. }
  56637. }
  56638. // Return mesh
  56639. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  56640. vertexData.applyToMesh(decal);
  56641. decal.position = position.clone();
  56642. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  56643. return decal;
  56644. };
  56645. // Privates
  56646. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  56647. // extrusion geometry
  56648. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  56649. var tangents = path3D.getTangents();
  56650. var normals = path3D.getNormals();
  56651. var binormals = path3D.getBinormals();
  56652. var distances = path3D.getDistances();
  56653. var angle = 0;
  56654. var returnScale = function () { return scale !== null ? scale : 1; };
  56655. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  56656. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  56657. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  56658. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  56659. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  56660. for (var i = 0; i < curve.length; i++) {
  56661. var shapePath = new Array();
  56662. var angleStep = rotate(i, distances[i]);
  56663. var scaleRatio = scl(i, distances[i]);
  56664. for (var p = 0; p < shape.length; p++) {
  56665. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  56666. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  56667. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  56668. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  56669. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  56670. shapePath[p] = rotated;
  56671. }
  56672. shapePaths[index] = shapePath;
  56673. angle += angleStep;
  56674. index++;
  56675. }
  56676. // cap
  56677. var capPath = function (shapePath) {
  56678. var pointCap = Array();
  56679. var barycenter = BABYLON.Vector3.Zero();
  56680. var i;
  56681. for (i = 0; i < shapePath.length; i++) {
  56682. barycenter.addInPlace(shapePath[i]);
  56683. }
  56684. barycenter.scaleInPlace(1.0 / shapePath.length);
  56685. for (i = 0; i < shapePath.length; i++) {
  56686. pointCap.push(barycenter);
  56687. }
  56688. return pointCap;
  56689. };
  56690. switch (cap) {
  56691. case BABYLON.Mesh.NO_CAP:
  56692. break;
  56693. case BABYLON.Mesh.CAP_START:
  56694. shapePaths[0] = capPath(shapePaths[2]);
  56695. shapePaths[1] = shapePaths[2];
  56696. break;
  56697. case BABYLON.Mesh.CAP_END:
  56698. shapePaths[index] = shapePaths[index - 1];
  56699. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56700. break;
  56701. case BABYLON.Mesh.CAP_ALL:
  56702. shapePaths[0] = capPath(shapePaths[2]);
  56703. shapePaths[1] = shapePaths[2];
  56704. shapePaths[index] = shapePaths[index - 1];
  56705. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  56706. break;
  56707. default:
  56708. break;
  56709. }
  56710. return shapePaths;
  56711. };
  56712. var path3D;
  56713. var pathArray;
  56714. if (instance) {
  56715. path3D = (instance.path3D).update(curve);
  56716. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56717. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56718. return instance;
  56719. }
  56720. // extruded shape creation
  56721. path3D = new BABYLON.Path3D(curve);
  56722. var newShapePaths = new Array();
  56723. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56724. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56725. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56726. extrudedGeneric.pathArray = pathArray;
  56727. extrudedGeneric.path3D = path3D;
  56728. extrudedGeneric.cap = cap;
  56729. return extrudedGeneric;
  56730. };
  56731. return MeshBuilder;
  56732. }());
  56733. BABYLON.MeshBuilder = MeshBuilder;
  56734. })(BABYLON || (BABYLON = {}));
  56735. //# sourceMappingURL=babylon.meshBuilder.js.map
  56736. "use strict";
  56737. var BABYLON;
  56738. (function (BABYLON) {
  56739. /**
  56740. * Draco compression (https://google.github.io/draco/)
  56741. */
  56742. var DracoCompression = /** @class */ (function () {
  56743. /**
  56744. * Constructor
  56745. * @param numWorkers The number of workers for async operations
  56746. */
  56747. function DracoCompression(numWorkers) {
  56748. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  56749. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  56750. if (!workerBlobUrl || !Worker) {
  56751. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  56752. return;
  56753. }
  56754. var workers = new Array(numWorkers);
  56755. for (var i = 0; i < workers.length; i++) {
  56756. var worker = new Worker(workerBlobUrl);
  56757. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  56758. workers[i] = worker;
  56759. }
  56760. this._workerPool = new BABYLON.WorkerPool(workers);
  56761. }
  56762. /**
  56763. * Stop all async operations and release resources.
  56764. */
  56765. DracoCompression.prototype.dispose = function () {
  56766. this._workerPool.dispose();
  56767. delete this._workerPool;
  56768. };
  56769. /**
  56770. * Decode Draco compressed mesh data to vertex data.
  56771. * @param data The array buffer view for the Draco compression data
  56772. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56773. * @returns A promise that resolves with the decoded vertex data
  56774. */
  56775. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  56776. var _this = this;
  56777. return new Promise(function (resolve, reject) {
  56778. _this._workerPool.push(function (worker, onComplete) {
  56779. var vertexData = new BABYLON.VertexData();
  56780. var onError = function (error) {
  56781. worker.removeEventListener("error", onError);
  56782. worker.removeEventListener("message", onMessage);
  56783. reject(error);
  56784. onComplete();
  56785. };
  56786. var onMessage = function (message) {
  56787. if (message.data === "done") {
  56788. worker.removeEventListener("error", onError);
  56789. worker.removeEventListener("message", onMessage);
  56790. resolve(vertexData);
  56791. onComplete();
  56792. }
  56793. else if (message.data.id === "indices") {
  56794. vertexData.indices = message.data.value;
  56795. }
  56796. else {
  56797. vertexData.set(message.data.value, message.data.id);
  56798. }
  56799. };
  56800. worker.addEventListener("error", onError);
  56801. worker.addEventListener("message", onMessage);
  56802. var dataCopy = new Uint8Array(data.byteLength);
  56803. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  56804. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  56805. });
  56806. });
  56807. };
  56808. /**
  56809. * The worker function that gets converted to a blob url to pass into a worker.
  56810. */
  56811. DracoCompression._Worker = function () {
  56812. // self is actually a DedicatedWorkerGlobalScope
  56813. var _self = self;
  56814. var decodeMesh = function (data, attributes) {
  56815. var dracoModule = new DracoDecoderModule();
  56816. var buffer = new dracoModule.DecoderBuffer();
  56817. buffer.Init(data, data.byteLength);
  56818. var decoder = new dracoModule.Decoder();
  56819. var geometry;
  56820. var status;
  56821. try {
  56822. var type = decoder.GetEncodedGeometryType(buffer);
  56823. switch (type) {
  56824. case dracoModule.TRIANGULAR_MESH:
  56825. geometry = new dracoModule.Mesh();
  56826. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56827. break;
  56828. case dracoModule.POINT_CLOUD:
  56829. geometry = new dracoModule.PointCloud();
  56830. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56831. break;
  56832. default:
  56833. throw new Error("Invalid geometry type " + type);
  56834. }
  56835. if (!status.ok() || !geometry.ptr) {
  56836. throw new Error(status.error_msg());
  56837. }
  56838. var numPoints = geometry.num_points();
  56839. if (type === dracoModule.TRIANGULAR_MESH) {
  56840. var numFaces = geometry.num_faces();
  56841. var faceIndices = new dracoModule.DracoInt32Array();
  56842. try {
  56843. var indices = new Uint32Array(numFaces * 3);
  56844. for (var i = 0; i < numFaces; i++) {
  56845. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56846. var offset = i * 3;
  56847. indices[offset + 0] = faceIndices.GetValue(0);
  56848. indices[offset + 1] = faceIndices.GetValue(1);
  56849. indices[offset + 2] = faceIndices.GetValue(2);
  56850. }
  56851. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  56852. }
  56853. finally {
  56854. dracoModule.destroy(faceIndices);
  56855. }
  56856. }
  56857. for (var kind in attributes) {
  56858. var uniqueId = attributes[kind];
  56859. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56860. var dracoData = new dracoModule.DracoFloat32Array();
  56861. try {
  56862. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56863. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56864. for (var i = 0; i < babylonData.length; i++) {
  56865. babylonData[i] = dracoData.GetValue(i);
  56866. }
  56867. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  56868. }
  56869. finally {
  56870. dracoModule.destroy(dracoData);
  56871. }
  56872. }
  56873. }
  56874. finally {
  56875. if (geometry) {
  56876. dracoModule.destroy(geometry);
  56877. }
  56878. dracoModule.destroy(decoder);
  56879. dracoModule.destroy(buffer);
  56880. }
  56881. _self.postMessage("done");
  56882. };
  56883. _self.onmessage = function (event) {
  56884. switch (event.data.id) {
  56885. case "initDecoder": {
  56886. importScripts(event.data.url);
  56887. break;
  56888. }
  56889. case "decodeMesh": {
  56890. decodeMesh(event.data.data, event.data.attributes);
  56891. break;
  56892. }
  56893. }
  56894. };
  56895. };
  56896. DracoCompression._GetDefaultDecoderUrl = function () {
  56897. if (!BABYLON.Tools.IsWindowObjectExist) {
  56898. return null;
  56899. }
  56900. for (var i = 0; i < document.scripts.length; i++) {
  56901. if (document.scripts[i].type === "text/x-draco-decoder") {
  56902. return document.scripts[i].src;
  56903. }
  56904. }
  56905. return null;
  56906. };
  56907. /**
  56908. * Gets the url to the draco decoder if available.
  56909. */
  56910. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  56911. return DracoCompression;
  56912. }());
  56913. BABYLON.DracoCompression = DracoCompression;
  56914. })(BABYLON || (BABYLON = {}));
  56915. //# sourceMappingURL=babylon.dracoCompression.js.map
  56916. "use strict";
  56917. var BABYLON;
  56918. (function (BABYLON) {
  56919. var AudioEngine = /** @class */ (function () {
  56920. function AudioEngine() {
  56921. this._audioContext = null;
  56922. this._audioContextInitialized = false;
  56923. this.canUseWebAudio = false;
  56924. this.WarnedWebAudioUnsupported = false;
  56925. this.unlocked = false;
  56926. this.isMP3supported = false;
  56927. this.isOGGsupported = false;
  56928. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56929. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56930. this.canUseWebAudio = true;
  56931. }
  56932. var audioElem = document.createElement('audio');
  56933. try {
  56934. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56935. this.isMP3supported = true;
  56936. }
  56937. }
  56938. catch (e) {
  56939. // protect error during capability check.
  56940. }
  56941. try {
  56942. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56943. this.isOGGsupported = true;
  56944. }
  56945. }
  56946. catch (e) {
  56947. // protect error during capability check.
  56948. }
  56949. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56950. this._unlockiOSaudio();
  56951. }
  56952. else {
  56953. this.unlocked = true;
  56954. }
  56955. }
  56956. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56957. get: function () {
  56958. if (!this._audioContextInitialized) {
  56959. this._initializeAudioContext();
  56960. }
  56961. return this._audioContext;
  56962. },
  56963. enumerable: true,
  56964. configurable: true
  56965. });
  56966. AudioEngine.prototype._unlockiOSaudio = function () {
  56967. var _this = this;
  56968. var unlockaudio = function () {
  56969. if (!_this.audioContext) {
  56970. return;
  56971. }
  56972. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56973. var source = _this.audioContext.createBufferSource();
  56974. source.buffer = buffer;
  56975. source.connect(_this.audioContext.destination);
  56976. source.start(0);
  56977. setTimeout(function () {
  56978. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56979. _this.unlocked = true;
  56980. window.removeEventListener('touchend', unlockaudio, false);
  56981. if (_this.onAudioUnlocked) {
  56982. _this.onAudioUnlocked();
  56983. }
  56984. }
  56985. }, 0);
  56986. };
  56987. window.addEventListener('touchend', unlockaudio, false);
  56988. };
  56989. AudioEngine.prototype._initializeAudioContext = function () {
  56990. try {
  56991. if (this.canUseWebAudio) {
  56992. this._audioContext = new AudioContext();
  56993. // create a global volume gain node
  56994. this.masterGain = this._audioContext.createGain();
  56995. this.masterGain.gain.value = 1;
  56996. this.masterGain.connect(this._audioContext.destination);
  56997. this._audioContextInitialized = true;
  56998. }
  56999. }
  57000. catch (e) {
  57001. this.canUseWebAudio = false;
  57002. BABYLON.Tools.Error("Web Audio: " + e.message);
  57003. }
  57004. };
  57005. AudioEngine.prototype.dispose = function () {
  57006. if (this.canUseWebAudio && this._audioContextInitialized) {
  57007. if (this._connectedAnalyser && this._audioContext) {
  57008. this._connectedAnalyser.stopDebugCanvas();
  57009. this._connectedAnalyser.dispose();
  57010. this.masterGain.disconnect();
  57011. this.masterGain.connect(this._audioContext.destination);
  57012. this._connectedAnalyser = null;
  57013. }
  57014. this.masterGain.gain.value = 1;
  57015. }
  57016. this.WarnedWebAudioUnsupported = false;
  57017. };
  57018. AudioEngine.prototype.getGlobalVolume = function () {
  57019. if (this.canUseWebAudio && this._audioContextInitialized) {
  57020. return this.masterGain.gain.value;
  57021. }
  57022. else {
  57023. return -1;
  57024. }
  57025. };
  57026. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57027. if (this.canUseWebAudio && this._audioContextInitialized) {
  57028. this.masterGain.gain.value = newVolume;
  57029. }
  57030. };
  57031. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57032. if (this._connectedAnalyser) {
  57033. this._connectedAnalyser.stopDebugCanvas();
  57034. }
  57035. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57036. this._connectedAnalyser = analyser;
  57037. this.masterGain.disconnect();
  57038. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57039. }
  57040. };
  57041. return AudioEngine;
  57042. }());
  57043. BABYLON.AudioEngine = AudioEngine;
  57044. })(BABYLON || (BABYLON = {}));
  57045. //# sourceMappingURL=babylon.audioEngine.js.map
  57046. "use strict";
  57047. var BABYLON;
  57048. (function (BABYLON) {
  57049. var Sound = /** @class */ (function () {
  57050. /**
  57051. * Create a sound and attach it to a scene
  57052. * @param name Name of your sound
  57053. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57054. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57055. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57056. */
  57057. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57058. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57059. var _this = this;
  57060. this.autoplay = false;
  57061. this.loop = false;
  57062. this.useCustomAttenuation = false;
  57063. this.spatialSound = false;
  57064. this.refDistance = 1;
  57065. this.rolloffFactor = 1;
  57066. this.maxDistance = 100;
  57067. this.distanceModel = "linear";
  57068. this._panningModel = "equalpower";
  57069. this._playbackRate = 1;
  57070. this._streaming = false;
  57071. this._startTime = 0;
  57072. this._startOffset = 0;
  57073. this._position = BABYLON.Vector3.Zero();
  57074. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57075. this._volume = 1;
  57076. this._isReadyToPlay = false;
  57077. this.isPlaying = false;
  57078. this.isPaused = false;
  57079. this._isDirectional = false;
  57080. // Used if you'd like to create a directional sound.
  57081. // If not set, the sound will be omnidirectional
  57082. this._coneInnerAngle = 360;
  57083. this._coneOuterAngle = 360;
  57084. this._coneOuterGain = 0;
  57085. this._isOutputConnected = false;
  57086. this._urlType = "Unknown";
  57087. this.name = name;
  57088. this._scene = scene;
  57089. this._readyToPlayCallback = readyToPlayCallback;
  57090. // Default custom attenuation function is a linear attenuation
  57091. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57092. if (currentDistance < maxDistance) {
  57093. return currentVolume * (1 - currentDistance / maxDistance);
  57094. }
  57095. else {
  57096. return 0;
  57097. }
  57098. };
  57099. if (options) {
  57100. this.autoplay = options.autoplay || false;
  57101. this.loop = options.loop || false;
  57102. // if volume === 0, we need another way to check this option
  57103. if (options.volume !== undefined) {
  57104. this._volume = options.volume;
  57105. }
  57106. this.spatialSound = options.spatialSound || false;
  57107. this.maxDistance = options.maxDistance || 100;
  57108. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57109. this.rolloffFactor = options.rolloffFactor || 1;
  57110. this.refDistance = options.refDistance || 1;
  57111. this.distanceModel = options.distanceModel || "linear";
  57112. this._playbackRate = options.playbackRate || 1;
  57113. this._streaming = options.streaming || false;
  57114. }
  57115. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57116. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57117. this._soundGain.gain.value = this._volume;
  57118. this._inputAudioNode = this._soundGain;
  57119. this._ouputAudioNode = this._soundGain;
  57120. if (this.spatialSound) {
  57121. this._createSpatialParameters();
  57122. }
  57123. this._scene.mainSoundTrack.AddSound(this);
  57124. var validParameter = true;
  57125. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57126. if (urlOrArrayBuffer) {
  57127. if (typeof (urlOrArrayBuffer) === "string")
  57128. this._urlType = "String";
  57129. if (Array.isArray(urlOrArrayBuffer))
  57130. this._urlType = "Array";
  57131. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57132. this._urlType = "ArrayBuffer";
  57133. var urls = [];
  57134. var codecSupportedFound = false;
  57135. switch (this._urlType) {
  57136. case "ArrayBuffer":
  57137. if (urlOrArrayBuffer.byteLength > 0) {
  57138. codecSupportedFound = true;
  57139. this._soundLoaded(urlOrArrayBuffer);
  57140. }
  57141. break;
  57142. case "String":
  57143. urls.push(urlOrArrayBuffer);
  57144. case "Array":
  57145. if (urls.length === 0)
  57146. urls = urlOrArrayBuffer;
  57147. // If we found a supported format, we load it immediately and stop the loop
  57148. for (var i = 0; i < urls.length; i++) {
  57149. var url = urls[i];
  57150. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57151. codecSupportedFound = true;
  57152. }
  57153. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57154. codecSupportedFound = true;
  57155. }
  57156. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57157. codecSupportedFound = true;
  57158. }
  57159. if (url.indexOf("blob:") !== -1) {
  57160. codecSupportedFound = true;
  57161. }
  57162. if (codecSupportedFound) {
  57163. // Loading sound using XHR2
  57164. if (!this._streaming) {
  57165. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57166. }
  57167. else {
  57168. this._htmlAudioElement = new Audio(url);
  57169. this._htmlAudioElement.controls = false;
  57170. this._htmlAudioElement.loop = this.loop;
  57171. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57172. this._htmlAudioElement.preload = "auto";
  57173. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57174. _this._isReadyToPlay = true;
  57175. if (_this.autoplay) {
  57176. _this.play();
  57177. }
  57178. if (_this._readyToPlayCallback) {
  57179. _this._readyToPlayCallback();
  57180. }
  57181. });
  57182. document.body.appendChild(this._htmlAudioElement);
  57183. }
  57184. break;
  57185. }
  57186. }
  57187. break;
  57188. default:
  57189. validParameter = false;
  57190. break;
  57191. }
  57192. if (!validParameter) {
  57193. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57194. }
  57195. else {
  57196. if (!codecSupportedFound) {
  57197. this._isReadyToPlay = true;
  57198. // Simulating a ready to play event to avoid breaking code path
  57199. if (this._readyToPlayCallback) {
  57200. window.setTimeout(function () {
  57201. if (_this._readyToPlayCallback) {
  57202. _this._readyToPlayCallback();
  57203. }
  57204. }, 1000);
  57205. }
  57206. }
  57207. }
  57208. }
  57209. }
  57210. else {
  57211. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57212. this._scene.mainSoundTrack.AddSound(this);
  57213. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57214. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57215. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57216. }
  57217. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57218. if (this._readyToPlayCallback) {
  57219. window.setTimeout(function () {
  57220. if (_this._readyToPlayCallback) {
  57221. _this._readyToPlayCallback();
  57222. }
  57223. }, 1000);
  57224. }
  57225. }
  57226. }
  57227. Sound.prototype.dispose = function () {
  57228. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57229. if (this.isPlaying) {
  57230. this.stop();
  57231. }
  57232. this._isReadyToPlay = false;
  57233. if (this.soundTrackId === -1) {
  57234. this._scene.mainSoundTrack.RemoveSound(this);
  57235. }
  57236. else {
  57237. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57238. }
  57239. if (this._soundGain) {
  57240. this._soundGain.disconnect();
  57241. this._soundGain = null;
  57242. }
  57243. if (this._soundPanner) {
  57244. this._soundPanner.disconnect();
  57245. this._soundPanner = null;
  57246. }
  57247. if (this._soundSource) {
  57248. this._soundSource.disconnect();
  57249. this._soundSource = null;
  57250. }
  57251. this._audioBuffer = null;
  57252. if (this._htmlAudioElement) {
  57253. this._htmlAudioElement.pause();
  57254. this._htmlAudioElement.src = "";
  57255. document.body.removeChild(this._htmlAudioElement);
  57256. }
  57257. if (this._connectedMesh && this._registerFunc) {
  57258. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57259. this._connectedMesh = null;
  57260. }
  57261. }
  57262. };
  57263. Sound.prototype.isReady = function () {
  57264. return this._isReadyToPlay;
  57265. };
  57266. Sound.prototype._soundLoaded = function (audioData) {
  57267. var _this = this;
  57268. if (!BABYLON.Engine.audioEngine.audioContext) {
  57269. return;
  57270. }
  57271. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57272. _this._audioBuffer = buffer;
  57273. _this._isReadyToPlay = true;
  57274. if (_this.autoplay) {
  57275. _this.play();
  57276. }
  57277. if (_this._readyToPlayCallback) {
  57278. _this._readyToPlayCallback();
  57279. }
  57280. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57281. };
  57282. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57283. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57284. this._audioBuffer = audioBuffer;
  57285. this._isReadyToPlay = true;
  57286. }
  57287. };
  57288. Sound.prototype.updateOptions = function (options) {
  57289. if (options) {
  57290. this.loop = options.loop || this.loop;
  57291. this.maxDistance = options.maxDistance || this.maxDistance;
  57292. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57293. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57294. this.refDistance = options.refDistance || this.refDistance;
  57295. this.distanceModel = options.distanceModel || this.distanceModel;
  57296. this._playbackRate = options.playbackRate || this._playbackRate;
  57297. this._updateSpatialParameters();
  57298. if (this.isPlaying) {
  57299. if (this._streaming) {
  57300. this._htmlAudioElement.playbackRate = this._playbackRate;
  57301. }
  57302. else {
  57303. if (this._soundSource) {
  57304. this._soundSource.playbackRate.value = this._playbackRate;
  57305. }
  57306. }
  57307. }
  57308. }
  57309. };
  57310. Sound.prototype._createSpatialParameters = function () {
  57311. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57312. if (this._scene.headphone) {
  57313. this._panningModel = "HRTF";
  57314. }
  57315. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  57316. this._updateSpatialParameters();
  57317. this._soundPanner.connect(this._ouputAudioNode);
  57318. this._inputAudioNode = this._soundPanner;
  57319. }
  57320. };
  57321. Sound.prototype._updateSpatialParameters = function () {
  57322. if (this.spatialSound && this._soundPanner) {
  57323. if (this.useCustomAttenuation) {
  57324. // Tricks to disable in a way embedded Web Audio attenuation
  57325. this._soundPanner.distanceModel = "linear";
  57326. this._soundPanner.maxDistance = Number.MAX_VALUE;
  57327. this._soundPanner.refDistance = 1;
  57328. this._soundPanner.rolloffFactor = 1;
  57329. this._soundPanner.panningModel = this._panningModel;
  57330. }
  57331. else {
  57332. this._soundPanner.distanceModel = this.distanceModel;
  57333. this._soundPanner.maxDistance = this.maxDistance;
  57334. this._soundPanner.refDistance = this.refDistance;
  57335. this._soundPanner.rolloffFactor = this.rolloffFactor;
  57336. this._soundPanner.panningModel = this._panningModel;
  57337. }
  57338. }
  57339. };
  57340. Sound.prototype.switchPanningModelToHRTF = function () {
  57341. this._panningModel = "HRTF";
  57342. this._switchPanningModel();
  57343. };
  57344. Sound.prototype.switchPanningModelToEqualPower = function () {
  57345. this._panningModel = "equalpower";
  57346. this._switchPanningModel();
  57347. };
  57348. Sound.prototype._switchPanningModel = function () {
  57349. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57350. this._soundPanner.panningModel = this._panningModel;
  57351. }
  57352. };
  57353. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  57354. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57355. if (this._isOutputConnected) {
  57356. this._ouputAudioNode.disconnect();
  57357. }
  57358. this._ouputAudioNode.connect(soundTrackAudioNode);
  57359. this._isOutputConnected = true;
  57360. }
  57361. };
  57362. /**
  57363. * Transform this sound into a directional source
  57364. * @param coneInnerAngle Size of the inner cone in degree
  57365. * @param coneOuterAngle Size of the outer cone in degree
  57366. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  57367. */
  57368. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  57369. if (coneOuterAngle < coneInnerAngle) {
  57370. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  57371. return;
  57372. }
  57373. this._coneInnerAngle = coneInnerAngle;
  57374. this._coneOuterAngle = coneOuterAngle;
  57375. this._coneOuterGain = coneOuterGain;
  57376. this._isDirectional = true;
  57377. if (this.isPlaying && this.loop) {
  57378. this.stop();
  57379. this.play();
  57380. }
  57381. };
  57382. Sound.prototype.setPosition = function (newPosition) {
  57383. this._position = newPosition;
  57384. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  57385. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57386. }
  57387. };
  57388. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  57389. this._localDirection = newLocalDirection;
  57390. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  57391. this._updateDirection();
  57392. }
  57393. };
  57394. Sound.prototype._updateDirection = function () {
  57395. if (!this._connectedMesh || !this._soundPanner) {
  57396. return;
  57397. }
  57398. var mat = this._connectedMesh.getWorldMatrix();
  57399. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  57400. direction.normalize();
  57401. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  57402. };
  57403. Sound.prototype.updateDistanceFromListener = function () {
  57404. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  57405. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  57406. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  57407. }
  57408. };
  57409. Sound.prototype.setAttenuationFunction = function (callback) {
  57410. this._customAttenuationFunction = callback;
  57411. };
  57412. /**
  57413. * Play the sound
  57414. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  57415. * @param offset (optional) Start the sound setting it at a specific time
  57416. */
  57417. Sound.prototype.play = function (time, offset) {
  57418. var _this = this;
  57419. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  57420. try {
  57421. if (this._startOffset < 0) {
  57422. time = -this._startOffset;
  57423. this._startOffset = 0;
  57424. }
  57425. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57426. if (!this._soundSource || !this._streamingSource) {
  57427. if (this.spatialSound && this._soundPanner) {
  57428. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  57429. if (this._isDirectional) {
  57430. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  57431. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  57432. this._soundPanner.coneOuterGain = this._coneOuterGain;
  57433. if (this._connectedMesh) {
  57434. this._updateDirection();
  57435. }
  57436. else {
  57437. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  57438. }
  57439. }
  57440. }
  57441. }
  57442. if (this._streaming) {
  57443. if (!this._streamingSource) {
  57444. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  57445. this._htmlAudioElement.onended = function () { _this._onended(); };
  57446. this._htmlAudioElement.playbackRate = this._playbackRate;
  57447. }
  57448. this._streamingSource.disconnect();
  57449. this._streamingSource.connect(this._inputAudioNode);
  57450. this._htmlAudioElement.play();
  57451. }
  57452. else {
  57453. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  57454. this._soundSource.buffer = this._audioBuffer;
  57455. this._soundSource.connect(this._inputAudioNode);
  57456. this._soundSource.loop = this.loop;
  57457. this._soundSource.playbackRate.value = this._playbackRate;
  57458. this._soundSource.onended = function () { _this._onended(); };
  57459. if (this._soundSource.buffer) {
  57460. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  57461. }
  57462. }
  57463. this._startTime = startTime;
  57464. this.isPlaying = true;
  57465. this.isPaused = false;
  57466. }
  57467. catch (ex) {
  57468. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  57469. }
  57470. }
  57471. };
  57472. Sound.prototype._onended = function () {
  57473. this.isPlaying = false;
  57474. if (this.onended) {
  57475. this.onended();
  57476. }
  57477. };
  57478. /**
  57479. * Stop the sound
  57480. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  57481. */
  57482. Sound.prototype.stop = function (time) {
  57483. if (this.isPlaying) {
  57484. if (this._streaming) {
  57485. this._htmlAudioElement.pause();
  57486. // Test needed for Firefox or it will generate an Invalid State Error
  57487. if (this._htmlAudioElement.currentTime > 0) {
  57488. this._htmlAudioElement.currentTime = 0;
  57489. }
  57490. }
  57491. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  57492. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  57493. this._soundSource.stop(stopTime);
  57494. this._soundSource.onended = function () { };
  57495. if (!this.isPaused) {
  57496. this._startOffset = 0;
  57497. }
  57498. }
  57499. this.isPlaying = false;
  57500. }
  57501. };
  57502. Sound.prototype.pause = function () {
  57503. if (this.isPlaying) {
  57504. this.isPaused = true;
  57505. if (this._streaming) {
  57506. this._htmlAudioElement.pause();
  57507. }
  57508. else if (BABYLON.Engine.audioEngine.audioContext) {
  57509. this.stop(0);
  57510. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  57511. }
  57512. }
  57513. };
  57514. Sound.prototype.setVolume = function (newVolume, time) {
  57515. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  57516. if (time && BABYLON.Engine.audioEngine.audioContext) {
  57517. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  57518. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  57519. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  57520. }
  57521. else {
  57522. this._soundGain.gain.value = newVolume;
  57523. }
  57524. }
  57525. this._volume = newVolume;
  57526. };
  57527. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  57528. this._playbackRate = newPlaybackRate;
  57529. if (this.isPlaying) {
  57530. if (this._streaming) {
  57531. this._htmlAudioElement.playbackRate = this._playbackRate;
  57532. }
  57533. else if (this._soundSource) {
  57534. this._soundSource.playbackRate.value = this._playbackRate;
  57535. }
  57536. }
  57537. };
  57538. Sound.prototype.getVolume = function () {
  57539. return this._volume;
  57540. };
  57541. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  57542. var _this = this;
  57543. if (this._connectedMesh && this._registerFunc) {
  57544. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57545. this._registerFunc = null;
  57546. }
  57547. this._connectedMesh = meshToConnectTo;
  57548. if (!this.spatialSound) {
  57549. this.spatialSound = true;
  57550. this._createSpatialParameters();
  57551. if (this.isPlaying && this.loop) {
  57552. this.stop();
  57553. this.play();
  57554. }
  57555. }
  57556. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  57557. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  57558. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  57559. };
  57560. Sound.prototype.detachFromMesh = function () {
  57561. if (this._connectedMesh && this._registerFunc) {
  57562. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57563. this._registerFunc = null;
  57564. this._connectedMesh = null;
  57565. }
  57566. };
  57567. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  57568. if (!node.getBoundingInfo) {
  57569. return;
  57570. }
  57571. var mesh = node;
  57572. var boundingInfo = mesh.getBoundingInfo();
  57573. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  57574. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  57575. this._updateDirection();
  57576. }
  57577. };
  57578. Sound.prototype.clone = function () {
  57579. var _this = this;
  57580. if (!this._streaming) {
  57581. var setBufferAndRun = function () {
  57582. if (_this._isReadyToPlay) {
  57583. clonedSound._audioBuffer = _this.getAudioBuffer();
  57584. clonedSound._isReadyToPlay = true;
  57585. if (clonedSound.autoplay) {
  57586. clonedSound.play();
  57587. }
  57588. }
  57589. else {
  57590. window.setTimeout(setBufferAndRun, 300);
  57591. }
  57592. };
  57593. var currentOptions = {
  57594. autoplay: this.autoplay, loop: this.loop,
  57595. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  57596. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  57597. refDistance: this.refDistance, distanceModel: this.distanceModel
  57598. };
  57599. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  57600. if (this.useCustomAttenuation) {
  57601. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  57602. }
  57603. clonedSound.setPosition(this._position);
  57604. clonedSound.setPlaybackRate(this._playbackRate);
  57605. setBufferAndRun();
  57606. return clonedSound;
  57607. }
  57608. else {
  57609. return null;
  57610. }
  57611. };
  57612. Sound.prototype.getAudioBuffer = function () {
  57613. return this._audioBuffer;
  57614. };
  57615. Sound.prototype.serialize = function () {
  57616. var serializationObject = {
  57617. name: this.name,
  57618. url: this.name,
  57619. autoplay: this.autoplay,
  57620. loop: this.loop,
  57621. volume: this._volume,
  57622. spatialSound: this.spatialSound,
  57623. maxDistance: this.maxDistance,
  57624. rolloffFactor: this.rolloffFactor,
  57625. refDistance: this.refDistance,
  57626. distanceModel: this.distanceModel,
  57627. playbackRate: this._playbackRate,
  57628. panningModel: this._panningModel,
  57629. soundTrackId: this.soundTrackId
  57630. };
  57631. if (this.spatialSound) {
  57632. if (this._connectedMesh)
  57633. serializationObject.connectedMeshId = this._connectedMesh.id;
  57634. serializationObject.position = this._position.asArray();
  57635. serializationObject.refDistance = this.refDistance;
  57636. serializationObject.distanceModel = this.distanceModel;
  57637. serializationObject.isDirectional = this._isDirectional;
  57638. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  57639. serializationObject.coneInnerAngle = this._coneInnerAngle;
  57640. serializationObject.coneOuterAngle = this._coneOuterAngle;
  57641. serializationObject.coneOuterGain = this._coneOuterGain;
  57642. }
  57643. return serializationObject;
  57644. };
  57645. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  57646. var soundName = parsedSound.name;
  57647. var soundUrl;
  57648. if (parsedSound.url) {
  57649. soundUrl = rootUrl + parsedSound.url;
  57650. }
  57651. else {
  57652. soundUrl = rootUrl + soundName;
  57653. }
  57654. var options = {
  57655. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  57656. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  57657. rolloffFactor: parsedSound.rolloffFactor,
  57658. refDistance: parsedSound.refDistance,
  57659. distanceModel: parsedSound.distanceModel,
  57660. playbackRate: parsedSound.playbackRate
  57661. };
  57662. var newSound;
  57663. if (!sourceSound) {
  57664. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  57665. scene._addPendingData(newSound);
  57666. }
  57667. else {
  57668. var setBufferAndRun = function () {
  57669. if (sourceSound._isReadyToPlay) {
  57670. newSound._audioBuffer = sourceSound.getAudioBuffer();
  57671. newSound._isReadyToPlay = true;
  57672. if (newSound.autoplay) {
  57673. newSound.play();
  57674. }
  57675. }
  57676. else {
  57677. window.setTimeout(setBufferAndRun, 300);
  57678. }
  57679. };
  57680. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  57681. setBufferAndRun();
  57682. }
  57683. if (parsedSound.position) {
  57684. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  57685. newSound.setPosition(soundPosition);
  57686. }
  57687. if (parsedSound.isDirectional) {
  57688. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  57689. if (parsedSound.localDirectionToMesh) {
  57690. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  57691. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  57692. }
  57693. }
  57694. if (parsedSound.connectedMeshId) {
  57695. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  57696. if (connectedMesh) {
  57697. newSound.attachToMesh(connectedMesh);
  57698. }
  57699. }
  57700. return newSound;
  57701. };
  57702. return Sound;
  57703. }());
  57704. BABYLON.Sound = Sound;
  57705. })(BABYLON || (BABYLON = {}));
  57706. //# sourceMappingURL=babylon.sound.js.map
  57707. "use strict";
  57708. var BABYLON;
  57709. (function (BABYLON) {
  57710. var SoundTrack = /** @class */ (function () {
  57711. function SoundTrack(scene, options) {
  57712. this.id = -1;
  57713. this._isMainTrack = false;
  57714. this._isInitialized = false;
  57715. this._scene = scene;
  57716. this.soundCollection = new Array();
  57717. this._options = options;
  57718. if (!this._isMainTrack) {
  57719. this._scene.soundTracks.push(this);
  57720. this.id = this._scene.soundTracks.length - 1;
  57721. }
  57722. }
  57723. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  57724. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57725. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  57726. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  57727. if (this._options) {
  57728. if (this._options.volume) {
  57729. this._outputAudioNode.gain.value = this._options.volume;
  57730. }
  57731. if (this._options.mainTrack) {
  57732. this._isMainTrack = this._options.mainTrack;
  57733. }
  57734. }
  57735. this._isInitialized = true;
  57736. }
  57737. };
  57738. SoundTrack.prototype.dispose = function () {
  57739. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  57740. if (this._connectedAnalyser) {
  57741. this._connectedAnalyser.stopDebugCanvas();
  57742. }
  57743. while (this.soundCollection.length) {
  57744. this.soundCollection[0].dispose();
  57745. }
  57746. if (this._outputAudioNode) {
  57747. this._outputAudioNode.disconnect();
  57748. }
  57749. this._outputAudioNode = null;
  57750. }
  57751. };
  57752. SoundTrack.prototype.AddSound = function (sound) {
  57753. if (!this._isInitialized) {
  57754. this._initializeSoundTrackAudioGraph();
  57755. }
  57756. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57757. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  57758. }
  57759. if (sound.soundTrackId) {
  57760. if (sound.soundTrackId === -1) {
  57761. this._scene.mainSoundTrack.RemoveSound(sound);
  57762. }
  57763. else {
  57764. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  57765. }
  57766. }
  57767. this.soundCollection.push(sound);
  57768. sound.soundTrackId = this.id;
  57769. };
  57770. SoundTrack.prototype.RemoveSound = function (sound) {
  57771. var index = this.soundCollection.indexOf(sound);
  57772. if (index !== -1) {
  57773. this.soundCollection.splice(index, 1);
  57774. }
  57775. };
  57776. SoundTrack.prototype.setVolume = function (newVolume) {
  57777. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57778. this._outputAudioNode.gain.value = newVolume;
  57779. }
  57780. };
  57781. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  57782. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57783. for (var i = 0; i < this.soundCollection.length; i++) {
  57784. this.soundCollection[i].switchPanningModelToHRTF();
  57785. }
  57786. }
  57787. };
  57788. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57789. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57790. for (var i = 0; i < this.soundCollection.length; i++) {
  57791. this.soundCollection[i].switchPanningModelToEqualPower();
  57792. }
  57793. }
  57794. };
  57795. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57796. if (this._connectedAnalyser) {
  57797. this._connectedAnalyser.stopDebugCanvas();
  57798. }
  57799. this._connectedAnalyser = analyser;
  57800. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57801. this._outputAudioNode.disconnect();
  57802. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57803. }
  57804. };
  57805. return SoundTrack;
  57806. }());
  57807. BABYLON.SoundTrack = SoundTrack;
  57808. })(BABYLON || (BABYLON = {}));
  57809. //# sourceMappingURL=babylon.soundtrack.js.map
  57810. "use strict";
  57811. var BABYLON;
  57812. (function (BABYLON) {
  57813. var Analyser = /** @class */ (function () {
  57814. function Analyser(scene) {
  57815. this.SMOOTHING = 0.75;
  57816. this.FFT_SIZE = 512;
  57817. this.BARGRAPHAMPLITUDE = 256;
  57818. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57819. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57820. this._scene = scene;
  57821. this._audioEngine = BABYLON.Engine.audioEngine;
  57822. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57823. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57824. this._webAudioAnalyser.minDecibels = -140;
  57825. this._webAudioAnalyser.maxDecibels = 0;
  57826. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57827. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57828. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57829. }
  57830. }
  57831. Analyser.prototype.getFrequencyBinCount = function () {
  57832. if (this._audioEngine.canUseWebAudio) {
  57833. return this._webAudioAnalyser.frequencyBinCount;
  57834. }
  57835. else {
  57836. return 0;
  57837. }
  57838. };
  57839. Analyser.prototype.getByteFrequencyData = function () {
  57840. if (this._audioEngine.canUseWebAudio) {
  57841. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57842. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57843. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57844. }
  57845. return this._byteFreqs;
  57846. };
  57847. Analyser.prototype.getByteTimeDomainData = function () {
  57848. if (this._audioEngine.canUseWebAudio) {
  57849. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57850. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57851. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57852. }
  57853. return this._byteTime;
  57854. };
  57855. Analyser.prototype.getFloatFrequencyData = function () {
  57856. if (this._audioEngine.canUseWebAudio) {
  57857. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57858. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57859. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57860. }
  57861. return this._floatFreqs;
  57862. };
  57863. Analyser.prototype.drawDebugCanvas = function () {
  57864. var _this = this;
  57865. if (this._audioEngine.canUseWebAudio) {
  57866. if (!this._debugCanvas) {
  57867. this._debugCanvas = document.createElement("canvas");
  57868. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57869. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57870. this._debugCanvas.style.position = "absolute";
  57871. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57872. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57873. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57874. document.body.appendChild(this._debugCanvas);
  57875. this._registerFunc = function () {
  57876. _this.drawDebugCanvas();
  57877. };
  57878. this._scene.registerBeforeRender(this._registerFunc);
  57879. }
  57880. if (this._registerFunc && this._debugCanvasContext) {
  57881. var workingArray = this.getByteFrequencyData();
  57882. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57883. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57884. // Draw the frequency domain chart.
  57885. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57886. var value = workingArray[i];
  57887. var percent = value / this.BARGRAPHAMPLITUDE;
  57888. var height = this.DEBUGCANVASSIZE.height * percent;
  57889. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57890. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57891. var hue = i / this.getFrequencyBinCount() * 360;
  57892. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57893. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57894. }
  57895. }
  57896. }
  57897. };
  57898. Analyser.prototype.stopDebugCanvas = function () {
  57899. if (this._debugCanvas) {
  57900. if (this._registerFunc) {
  57901. this._scene.unregisterBeforeRender(this._registerFunc);
  57902. this._registerFunc = null;
  57903. }
  57904. document.body.removeChild(this._debugCanvas);
  57905. this._debugCanvas = null;
  57906. this._debugCanvasContext = null;
  57907. }
  57908. };
  57909. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57910. if (this._audioEngine.canUseWebAudio) {
  57911. inputAudioNode.connect(this._webAudioAnalyser);
  57912. this._webAudioAnalyser.connect(outputAudioNode);
  57913. }
  57914. };
  57915. Analyser.prototype.dispose = function () {
  57916. if (this._audioEngine.canUseWebAudio) {
  57917. this._webAudioAnalyser.disconnect();
  57918. }
  57919. };
  57920. return Analyser;
  57921. }());
  57922. BABYLON.Analyser = Analyser;
  57923. })(BABYLON || (BABYLON = {}));
  57924. //# sourceMappingURL=babylon.analyser.js.map
  57925. "use strict";
  57926. var BABYLON;
  57927. (function (BABYLON) {
  57928. var CubeTexture = /** @class */ (function (_super) {
  57929. __extends(CubeTexture, _super);
  57930. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57931. if (extensions === void 0) { extensions = null; }
  57932. if (noMipmap === void 0) { noMipmap = false; }
  57933. if (files === void 0) { files = null; }
  57934. if (onLoad === void 0) { onLoad = null; }
  57935. if (onError === void 0) { onError = null; }
  57936. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57937. if (prefiltered === void 0) { prefiltered = false; }
  57938. if (forcedExtension === void 0) { forcedExtension = null; }
  57939. var _this = _super.call(this, scene) || this;
  57940. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57941. /**
  57942. * Gets or sets the center of the bounding box associated with the cube texture
  57943. * It must define where the camera used to render the texture was set
  57944. */
  57945. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57946. _this.name = rootUrl;
  57947. _this.url = rootUrl;
  57948. _this._noMipmap = noMipmap;
  57949. _this.hasAlpha = false;
  57950. _this._format = format;
  57951. _this._prefiltered = prefiltered;
  57952. _this.isCube = true;
  57953. _this._textureMatrix = BABYLON.Matrix.Identity();
  57954. if (prefiltered) {
  57955. _this.gammaSpace = false;
  57956. }
  57957. if (!rootUrl && !files) {
  57958. return _this;
  57959. }
  57960. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57961. var lastDot = rootUrl.lastIndexOf(".");
  57962. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57963. var isDDS = (extension === ".dds");
  57964. if (!files) {
  57965. if (!isDDS && !extensions) {
  57966. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57967. }
  57968. files = [];
  57969. if (extensions) {
  57970. for (var index = 0; index < extensions.length; index++) {
  57971. files.push(rootUrl + extensions[index]);
  57972. }
  57973. }
  57974. }
  57975. _this._files = files;
  57976. if (!_this._texture) {
  57977. if (!scene.useDelayedTextureLoading) {
  57978. if (prefiltered) {
  57979. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57980. }
  57981. else {
  57982. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57983. }
  57984. }
  57985. else {
  57986. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57987. }
  57988. }
  57989. else if (onLoad) {
  57990. if (_this._texture.isReady) {
  57991. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57992. }
  57993. else {
  57994. _this._texture.onLoadedObservable.add(onLoad);
  57995. }
  57996. }
  57997. return _this;
  57998. }
  57999. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58000. get: function () {
  58001. return this._boundingBoxSize;
  58002. },
  58003. /**
  58004. * Gets or sets the size of the bounding box associated with the cube texture
  58005. * When defined, the cubemap will switch to local mode
  58006. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58007. * @example https://www.babylonjs-playground.com/#RNASML
  58008. */
  58009. set: function (value) {
  58010. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58011. return;
  58012. }
  58013. this._boundingBoxSize = value;
  58014. var scene = this.getScene();
  58015. if (scene) {
  58016. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58017. }
  58018. },
  58019. enumerable: true,
  58020. configurable: true
  58021. });
  58022. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58023. var rootUrlKey = "";
  58024. files.forEach(function (url) { return rootUrlKey += url; });
  58025. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58026. };
  58027. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58028. if (forcedExtension === void 0) { forcedExtension = null; }
  58029. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58030. };
  58031. // Methods
  58032. CubeTexture.prototype.delayLoad = function () {
  58033. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58034. return;
  58035. }
  58036. var scene = this.getScene();
  58037. if (!scene) {
  58038. return;
  58039. }
  58040. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58041. this._texture = this._getFromCache(this.url, this._noMipmap);
  58042. if (!this._texture) {
  58043. if (this._prefiltered) {
  58044. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58045. }
  58046. else {
  58047. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58048. }
  58049. }
  58050. };
  58051. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58052. return this._textureMatrix;
  58053. };
  58054. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58055. this._textureMatrix = value;
  58056. };
  58057. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58058. var texture = BABYLON.SerializationHelper.Parse(function () {
  58059. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58060. }, parsedTexture, scene);
  58061. // Local Cubemaps
  58062. if (parsedTexture.boundingBoxPosition) {
  58063. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58064. }
  58065. if (parsedTexture.boundingBoxSize) {
  58066. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58067. }
  58068. // Animations
  58069. if (parsedTexture.animations) {
  58070. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58071. var parsedAnimation = parsedTexture.animations[animationIndex];
  58072. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58073. }
  58074. }
  58075. return texture;
  58076. };
  58077. CubeTexture.prototype.clone = function () {
  58078. var _this = this;
  58079. return BABYLON.SerializationHelper.Clone(function () {
  58080. var scene = _this.getScene();
  58081. if (!scene) {
  58082. return _this;
  58083. }
  58084. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58085. }, this);
  58086. };
  58087. return CubeTexture;
  58088. }(BABYLON.BaseTexture));
  58089. BABYLON.CubeTexture = CubeTexture;
  58090. })(BABYLON || (BABYLON = {}));
  58091. //# sourceMappingURL=babylon.cubeTexture.js.map
  58092. "use strict";
  58093. var BABYLON;
  58094. (function (BABYLON) {
  58095. var RenderTargetTexture = /** @class */ (function (_super) {
  58096. __extends(RenderTargetTexture, _super);
  58097. /**
  58098. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58099. * or used a shadow, depth texture...
  58100. * @param name The friendly name of the texture
  58101. * @param size The size of the RTT (number if square, or {with: number, height:number} or {ratio:} to define a ratio from the main scene)
  58102. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58103. * @param generateMipMaps True if mip maps need to be generated after render.
  58104. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58105. * @param type The type of the buffer in the RTT (int, half float, float...)
  58106. * @param isCube True if a cube texture needs to be created
  58107. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58108. * @param generateDepthBuffer True to generate a depth buffer
  58109. * @param generateStencilBuffer True to generate a stencil buffer
  58110. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58111. */
  58112. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58113. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58114. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58115. if (isCube === void 0) { isCube = false; }
  58116. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58117. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58118. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58119. if (isMulti === void 0) { isMulti = false; }
  58120. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58121. _this.isCube = isCube;
  58122. /**
  58123. * Use this list to define the list of mesh you want to render.
  58124. */
  58125. _this.renderList = new Array();
  58126. _this.renderParticles = true;
  58127. _this.renderSprites = false;
  58128. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58129. _this.ignoreCameraViewport = false;
  58130. // Events
  58131. /**
  58132. * An event triggered when the texture is unbind.
  58133. * @type {BABYLON.Observable}
  58134. */
  58135. _this.onBeforeBindObservable = new BABYLON.Observable();
  58136. /**
  58137. * An event triggered when the texture is unbind.
  58138. * @type {BABYLON.Observable}
  58139. */
  58140. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58141. /**
  58142. * An event triggered before rendering the texture
  58143. * @type {BABYLON.Observable}
  58144. */
  58145. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58146. /**
  58147. * An event triggered after rendering the texture
  58148. * @type {BABYLON.Observable}
  58149. */
  58150. _this.onAfterRenderObservable = new BABYLON.Observable();
  58151. /**
  58152. * An event triggered after the texture clear
  58153. * @type {BABYLON.Observable}
  58154. */
  58155. _this.onClearObservable = new BABYLON.Observable();
  58156. _this._currentRefreshId = -1;
  58157. _this._refreshRate = 1;
  58158. _this._samples = 1;
  58159. /**
  58160. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58161. * It must define where the camera used to render the texture is set
  58162. */
  58163. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58164. scene = _this.getScene();
  58165. if (!scene) {
  58166. return _this;
  58167. }
  58168. _this._engine = scene.getEngine();
  58169. _this.name = name;
  58170. _this.isRenderTarget = true;
  58171. _this._initialSizeParameter = size;
  58172. _this._processSizeParameter(size);
  58173. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58174. });
  58175. _this._generateMipMaps = generateMipMaps ? true : false;
  58176. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58177. // Rendering groups
  58178. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58179. if (isMulti) {
  58180. return _this;
  58181. }
  58182. _this._renderTargetOptions = {
  58183. generateMipMaps: generateMipMaps,
  58184. type: type,
  58185. samplingMode: samplingMode,
  58186. generateDepthBuffer: generateDepthBuffer,
  58187. generateStencilBuffer: generateStencilBuffer
  58188. };
  58189. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58190. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58191. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58192. }
  58193. if (isCube) {
  58194. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58195. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58196. _this._textureMatrix = BABYLON.Matrix.Identity();
  58197. }
  58198. else {
  58199. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58200. }
  58201. return _this;
  58202. }
  58203. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58204. get: function () {
  58205. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58206. },
  58207. enumerable: true,
  58208. configurable: true
  58209. });
  58210. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58211. get: function () {
  58212. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58213. },
  58214. enumerable: true,
  58215. configurable: true
  58216. });
  58217. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58218. get: function () {
  58219. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58220. },
  58221. enumerable: true,
  58222. configurable: true
  58223. });
  58224. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58225. set: function (callback) {
  58226. if (this._onAfterUnbindObserver) {
  58227. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58228. }
  58229. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58230. },
  58231. enumerable: true,
  58232. configurable: true
  58233. });
  58234. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58235. set: function (callback) {
  58236. if (this._onBeforeRenderObserver) {
  58237. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58238. }
  58239. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58240. },
  58241. enumerable: true,
  58242. configurable: true
  58243. });
  58244. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58245. set: function (callback) {
  58246. if (this._onAfterRenderObserver) {
  58247. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58248. }
  58249. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58250. },
  58251. enumerable: true,
  58252. configurable: true
  58253. });
  58254. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58255. set: function (callback) {
  58256. if (this._onClearObserver) {
  58257. this.onClearObservable.remove(this._onClearObserver);
  58258. }
  58259. this._onClearObserver = this.onClearObservable.add(callback);
  58260. },
  58261. enumerable: true,
  58262. configurable: true
  58263. });
  58264. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58265. get: function () {
  58266. return this._renderTargetOptions;
  58267. },
  58268. enumerable: true,
  58269. configurable: true
  58270. });
  58271. RenderTargetTexture.prototype._onRatioRescale = function () {
  58272. if (this._sizeRatio) {
  58273. this.resize(this._initialSizeParameter);
  58274. }
  58275. };
  58276. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58277. get: function () {
  58278. return this._boundingBoxSize;
  58279. },
  58280. /**
  58281. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58282. * When defined, the cubemap will switch to local mode
  58283. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58284. * @example https://www.babylonjs-playground.com/#RNASML
  58285. */
  58286. set: function (value) {
  58287. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58288. return;
  58289. }
  58290. this._boundingBoxSize = value;
  58291. var scene = this.getScene();
  58292. if (scene) {
  58293. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58294. }
  58295. },
  58296. enumerable: true,
  58297. configurable: true
  58298. });
  58299. /**
  58300. * Creates a depth stencil texture.
  58301. * This is only available in WebGL 2 or with the depth texture extension available.
  58302. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  58303. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  58304. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  58305. */
  58306. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  58307. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  58308. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  58309. if (generateStencil === void 0) { generateStencil = false; }
  58310. if (!this.getScene()) {
  58311. return;
  58312. }
  58313. var engine = this.getScene().getEngine();
  58314. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  58315. bilinearFiltering: bilinearFiltering,
  58316. comparisonFunction: comparisonFunction,
  58317. generateStencil: generateStencil,
  58318. isCube: this.isCube
  58319. });
  58320. engine.setFrameBufferDepthStencilTexture(this);
  58321. };
  58322. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  58323. if (size.ratio) {
  58324. this._sizeRatio = size.ratio;
  58325. this._size = {
  58326. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  58327. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  58328. };
  58329. }
  58330. else {
  58331. this._size = size;
  58332. }
  58333. };
  58334. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  58335. get: function () {
  58336. return this._samples;
  58337. },
  58338. set: function (value) {
  58339. if (this._samples === value) {
  58340. return;
  58341. }
  58342. var scene = this.getScene();
  58343. if (!scene) {
  58344. return;
  58345. }
  58346. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  58347. },
  58348. enumerable: true,
  58349. configurable: true
  58350. });
  58351. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  58352. this._currentRefreshId = -1;
  58353. };
  58354. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  58355. get: function () {
  58356. return this._refreshRate;
  58357. },
  58358. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58359. set: function (value) {
  58360. this._refreshRate = value;
  58361. this.resetRefreshCounter();
  58362. },
  58363. enumerable: true,
  58364. configurable: true
  58365. });
  58366. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  58367. if (!this._postProcessManager) {
  58368. var scene = this.getScene();
  58369. if (!scene) {
  58370. return;
  58371. }
  58372. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  58373. this._postProcesses = new Array();
  58374. }
  58375. this._postProcesses.push(postProcess);
  58376. this._postProcesses[0].autoClear = false;
  58377. };
  58378. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  58379. if (!this._postProcesses) {
  58380. return;
  58381. }
  58382. if (dispose) {
  58383. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  58384. var postProcess = _a[_i];
  58385. postProcess.dispose();
  58386. }
  58387. }
  58388. this._postProcesses = [];
  58389. };
  58390. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  58391. if (!this._postProcesses) {
  58392. return;
  58393. }
  58394. var index = this._postProcesses.indexOf(postProcess);
  58395. if (index === -1) {
  58396. return;
  58397. }
  58398. this._postProcesses.splice(index, 1);
  58399. if (this._postProcesses.length > 0) {
  58400. this._postProcesses[0].autoClear = false;
  58401. }
  58402. };
  58403. RenderTargetTexture.prototype._shouldRender = function () {
  58404. if (this._currentRefreshId === -1) {
  58405. this._currentRefreshId = 1;
  58406. return true;
  58407. }
  58408. if (this.refreshRate === this._currentRefreshId) {
  58409. this._currentRefreshId = 1;
  58410. return true;
  58411. }
  58412. this._currentRefreshId++;
  58413. return false;
  58414. };
  58415. RenderTargetTexture.prototype.getRenderSize = function () {
  58416. if (this._size.width) {
  58417. return this._size.width;
  58418. }
  58419. return this._size;
  58420. };
  58421. RenderTargetTexture.prototype.getRenderWidth = function () {
  58422. if (this._size.width) {
  58423. return this._size.width;
  58424. }
  58425. return this._size;
  58426. };
  58427. RenderTargetTexture.prototype.getRenderHeight = function () {
  58428. if (this._size.width) {
  58429. return this._size.height;
  58430. }
  58431. return this._size;
  58432. };
  58433. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  58434. get: function () {
  58435. return true;
  58436. },
  58437. enumerable: true,
  58438. configurable: true
  58439. });
  58440. RenderTargetTexture.prototype.scale = function (ratio) {
  58441. var newSize = this.getRenderSize() * ratio;
  58442. this.resize(newSize);
  58443. };
  58444. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  58445. if (this.isCube) {
  58446. return this._textureMatrix;
  58447. }
  58448. return _super.prototype.getReflectionTextureMatrix.call(this);
  58449. };
  58450. RenderTargetTexture.prototype.resize = function (size) {
  58451. this.releaseInternalTexture();
  58452. var scene = this.getScene();
  58453. if (!scene) {
  58454. return;
  58455. }
  58456. this._processSizeParameter(size);
  58457. if (this.isCube) {
  58458. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  58459. }
  58460. else {
  58461. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  58462. }
  58463. };
  58464. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  58465. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  58466. if (dumpForDebug === void 0) { dumpForDebug = false; }
  58467. var scene = this.getScene();
  58468. if (!scene) {
  58469. return;
  58470. }
  58471. var engine = scene.getEngine();
  58472. if (this.useCameraPostProcesses !== undefined) {
  58473. useCameraPostProcess = this.useCameraPostProcesses;
  58474. }
  58475. if (this._waitingRenderList) {
  58476. this.renderList = [];
  58477. for (var index = 0; index < this._waitingRenderList.length; index++) {
  58478. var id = this._waitingRenderList[index];
  58479. var mesh_1 = scene.getMeshByID(id);
  58480. if (mesh_1) {
  58481. this.renderList.push(mesh_1);
  58482. }
  58483. }
  58484. delete this._waitingRenderList;
  58485. }
  58486. // Is predicate defined?
  58487. if (this.renderListPredicate) {
  58488. if (this.renderList) {
  58489. this.renderList.splice(0); // Clear previous renderList
  58490. }
  58491. else {
  58492. this.renderList = [];
  58493. }
  58494. var scene = this.getScene();
  58495. if (!scene) {
  58496. return;
  58497. }
  58498. var sceneMeshes = scene.meshes;
  58499. for (var index = 0; index < sceneMeshes.length; index++) {
  58500. var mesh = sceneMeshes[index];
  58501. if (this.renderListPredicate(mesh)) {
  58502. this.renderList.push(mesh);
  58503. }
  58504. }
  58505. }
  58506. this.onBeforeBindObservable.notifyObservers(this);
  58507. // Set custom projection.
  58508. // Needs to be before binding to prevent changing the aspect ratio.
  58509. var camera;
  58510. if (this.activeCamera) {
  58511. camera = this.activeCamera;
  58512. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58513. if (this.activeCamera !== scene.activeCamera) {
  58514. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  58515. }
  58516. }
  58517. else {
  58518. camera = scene.activeCamera;
  58519. if (camera) {
  58520. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  58521. }
  58522. }
  58523. // Prepare renderingManager
  58524. this._renderingManager.reset();
  58525. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  58526. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  58527. var sceneRenderId = scene.getRenderId();
  58528. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  58529. var mesh = currentRenderList[meshIndex];
  58530. if (mesh) {
  58531. if (!mesh.isReady(this.refreshRate === 0)) {
  58532. this.resetRefreshCounter();
  58533. continue;
  58534. }
  58535. mesh._preActivateForIntermediateRendering(sceneRenderId);
  58536. var isMasked = void 0;
  58537. if (!this.renderList && camera) {
  58538. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  58539. }
  58540. else {
  58541. isMasked = false;
  58542. }
  58543. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  58544. mesh._activate(sceneRenderId);
  58545. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  58546. var subMesh = mesh.subMeshes[subIndex];
  58547. scene._activeIndices.addCount(subMesh.indexCount, false);
  58548. this._renderingManager.dispatch(subMesh, mesh);
  58549. }
  58550. }
  58551. }
  58552. }
  58553. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  58554. var particleSystem = scene.particleSystems[particleIndex];
  58555. var emitter = particleSystem.emitter;
  58556. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  58557. continue;
  58558. }
  58559. if (currentRenderList.indexOf(emitter) >= 0) {
  58560. this._renderingManager.dispatchParticles(particleSystem);
  58561. }
  58562. }
  58563. if (this.isCube) {
  58564. for (var face = 0; face < 6; face++) {
  58565. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58566. scene.incrementRenderId();
  58567. scene.resetCachedMaterial();
  58568. }
  58569. }
  58570. else {
  58571. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  58572. }
  58573. this.onAfterUnbindObservable.notifyObservers(this);
  58574. if (scene.activeCamera) {
  58575. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  58576. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  58577. }
  58578. engine.setViewport(scene.activeCamera.viewport);
  58579. }
  58580. scene.resetCachedMaterial();
  58581. };
  58582. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  58583. var minimum = 128;
  58584. var x = renderDimension * scale;
  58585. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  58586. // Ensure we don't exceed the render dimension (while staying POT)
  58587. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  58588. };
  58589. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58590. var _this = this;
  58591. if (!this._texture) {
  58592. return;
  58593. }
  58594. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  58595. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58596. });
  58597. };
  58598. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  58599. var scene = this.getScene();
  58600. if (!scene) {
  58601. return;
  58602. }
  58603. var engine = scene.getEngine();
  58604. if (!this._texture) {
  58605. return;
  58606. }
  58607. // Bind
  58608. if (this._postProcessManager) {
  58609. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  58610. }
  58611. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  58612. if (this._texture) {
  58613. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  58614. }
  58615. }
  58616. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  58617. // Clear
  58618. if (this.onClearObservable.hasObservers()) {
  58619. this.onClearObservable.notifyObservers(engine);
  58620. }
  58621. else {
  58622. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  58623. }
  58624. if (!this._doNotChangeAspectRatio) {
  58625. scene.updateTransformMatrix(true);
  58626. }
  58627. // Render
  58628. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  58629. if (this._postProcessManager) {
  58630. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  58631. }
  58632. else if (useCameraPostProcess) {
  58633. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  58634. }
  58635. if (!this._doNotChangeAspectRatio) {
  58636. scene.updateTransformMatrix(true);
  58637. }
  58638. // Dump ?
  58639. if (dumpForDebug) {
  58640. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  58641. }
  58642. // Unbind
  58643. if (!this.isCube || faceIndex === 5) {
  58644. if (this.isCube) {
  58645. if (faceIndex === 5) {
  58646. engine.generateMipMapsForCubemap(this._texture);
  58647. }
  58648. }
  58649. this.unbindFrameBuffer(engine, faceIndex);
  58650. }
  58651. else {
  58652. this.onAfterRenderObservable.notifyObservers(faceIndex);
  58653. }
  58654. };
  58655. /**
  58656. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  58657. * This allowed control for front to back rendering or reversly depending of the special needs.
  58658. *
  58659. * @param renderingGroupId The rendering group id corresponding to its index
  58660. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  58661. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  58662. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  58663. */
  58664. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  58665. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  58666. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  58667. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  58668. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  58669. };
  58670. /**
  58671. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  58672. *
  58673. * @param renderingGroupId The rendering group id corresponding to its index
  58674. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  58675. */
  58676. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  58677. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  58678. };
  58679. RenderTargetTexture.prototype.clone = function () {
  58680. var textureSize = this.getSize();
  58681. 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);
  58682. // Base texture
  58683. newTexture.hasAlpha = this.hasAlpha;
  58684. newTexture.level = this.level;
  58685. // RenderTarget Texture
  58686. newTexture.coordinatesMode = this.coordinatesMode;
  58687. if (this.renderList) {
  58688. newTexture.renderList = this.renderList.slice(0);
  58689. }
  58690. return newTexture;
  58691. };
  58692. RenderTargetTexture.prototype.serialize = function () {
  58693. if (!this.name) {
  58694. return null;
  58695. }
  58696. var serializationObject = _super.prototype.serialize.call(this);
  58697. serializationObject.renderTargetSize = this.getRenderSize();
  58698. serializationObject.renderList = [];
  58699. if (this.renderList) {
  58700. for (var index = 0; index < this.renderList.length; index++) {
  58701. serializationObject.renderList.push(this.renderList[index].id);
  58702. }
  58703. }
  58704. return serializationObject;
  58705. };
  58706. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  58707. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  58708. var objBuffer = this.getInternalTexture();
  58709. var scene = this.getScene();
  58710. if (objBuffer && scene) {
  58711. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  58712. }
  58713. };
  58714. RenderTargetTexture.prototype.dispose = function () {
  58715. if (this._postProcessManager) {
  58716. this._postProcessManager.dispose();
  58717. this._postProcessManager = null;
  58718. }
  58719. this.clearPostProcesses(true);
  58720. if (this._resizeObserver) {
  58721. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  58722. this._resizeObserver = null;
  58723. }
  58724. this.renderList = null;
  58725. // Remove from custom render targets
  58726. var scene = this.getScene();
  58727. if (!scene) {
  58728. return;
  58729. }
  58730. var index = scene.customRenderTargets.indexOf(this);
  58731. if (index >= 0) {
  58732. scene.customRenderTargets.splice(index, 1);
  58733. }
  58734. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  58735. var camera = _a[_i];
  58736. index = camera.customRenderTargets.indexOf(this);
  58737. if (index >= 0) {
  58738. camera.customRenderTargets.splice(index, 1);
  58739. }
  58740. }
  58741. _super.prototype.dispose.call(this);
  58742. };
  58743. RenderTargetTexture.prototype._rebuild = function () {
  58744. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58745. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58746. }
  58747. if (this._postProcessManager) {
  58748. this._postProcessManager._rebuild();
  58749. }
  58750. };
  58751. /**
  58752. * Clear the info related to rendering groups preventing retention point in material dispose.
  58753. */
  58754. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  58755. if (this._renderingManager) {
  58756. this._renderingManager.freeRenderingGroups();
  58757. }
  58758. };
  58759. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  58760. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  58761. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  58762. return RenderTargetTexture;
  58763. }(BABYLON.Texture));
  58764. BABYLON.RenderTargetTexture = RenderTargetTexture;
  58765. })(BABYLON || (BABYLON = {}));
  58766. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  58767. "use strict";
  58768. var BABYLON;
  58769. (function (BABYLON) {
  58770. ;
  58771. var MultiRenderTarget = /** @class */ (function (_super) {
  58772. __extends(MultiRenderTarget, _super);
  58773. function MultiRenderTarget(name, size, count, scene, options) {
  58774. var _this = this;
  58775. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  58776. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  58777. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  58778. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  58779. _this._engine = scene.getEngine();
  58780. if (!_this.isSupported) {
  58781. _this.dispose();
  58782. return;
  58783. }
  58784. var types = [];
  58785. var samplingModes = [];
  58786. for (var i = 0; i < count; i++) {
  58787. if (options && options.types && options.types[i] !== undefined) {
  58788. types.push(options.types[i]);
  58789. }
  58790. else {
  58791. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  58792. }
  58793. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  58794. samplingModes.push(options.samplingModes[i]);
  58795. }
  58796. else {
  58797. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58798. }
  58799. }
  58800. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  58801. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  58802. _this._size = size;
  58803. _this._multiRenderTargetOptions = {
  58804. samplingModes: samplingModes,
  58805. generateMipMaps: generateMipMaps,
  58806. generateDepthBuffer: generateDepthBuffer,
  58807. generateStencilBuffer: generateStencilBuffer,
  58808. generateDepthTexture: generateDepthTexture,
  58809. types: types,
  58810. textureCount: count
  58811. };
  58812. _this._createInternalTextures();
  58813. _this._createTextures();
  58814. return _this;
  58815. }
  58816. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  58817. get: function () {
  58818. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  58819. },
  58820. enumerable: true,
  58821. configurable: true
  58822. });
  58823. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  58824. get: function () {
  58825. return this._textures;
  58826. },
  58827. enumerable: true,
  58828. configurable: true
  58829. });
  58830. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  58831. get: function () {
  58832. return this._textures[this._textures.length - 1];
  58833. },
  58834. enumerable: true,
  58835. configurable: true
  58836. });
  58837. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  58838. set: function (wrap) {
  58839. if (this._textures) {
  58840. for (var i = 0; i < this._textures.length; i++) {
  58841. this._textures[i].wrapU = wrap;
  58842. }
  58843. }
  58844. },
  58845. enumerable: true,
  58846. configurable: true
  58847. });
  58848. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58849. set: function (wrap) {
  58850. if (this._textures) {
  58851. for (var i = 0; i < this._textures.length; i++) {
  58852. this._textures[i].wrapV = wrap;
  58853. }
  58854. }
  58855. },
  58856. enumerable: true,
  58857. configurable: true
  58858. });
  58859. MultiRenderTarget.prototype._rebuild = function () {
  58860. this.releaseInternalTextures();
  58861. this._createInternalTextures();
  58862. for (var i = 0; i < this._internalTextures.length; i++) {
  58863. var texture = this._textures[i];
  58864. texture._texture = this._internalTextures[i];
  58865. }
  58866. // Keeps references to frame buffer and stencil/depth buffer
  58867. this._texture = this._internalTextures[0];
  58868. };
  58869. MultiRenderTarget.prototype._createInternalTextures = function () {
  58870. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58871. };
  58872. MultiRenderTarget.prototype._createTextures = function () {
  58873. this._textures = [];
  58874. for (var i = 0; i < this._internalTextures.length; i++) {
  58875. var texture = new BABYLON.Texture(null, this.getScene());
  58876. texture._texture = this._internalTextures[i];
  58877. this._textures.push(texture);
  58878. }
  58879. // Keeps references to frame buffer and stencil/depth buffer
  58880. this._texture = this._internalTextures[0];
  58881. };
  58882. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58883. get: function () {
  58884. return this._samples;
  58885. },
  58886. set: function (value) {
  58887. if (this._samples === value) {
  58888. return;
  58889. }
  58890. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58891. },
  58892. enumerable: true,
  58893. configurable: true
  58894. });
  58895. MultiRenderTarget.prototype.resize = function (size) {
  58896. this.releaseInternalTextures();
  58897. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58898. this._createInternalTextures();
  58899. };
  58900. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58901. var _this = this;
  58902. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58903. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58904. });
  58905. };
  58906. MultiRenderTarget.prototype.dispose = function () {
  58907. this.releaseInternalTextures();
  58908. _super.prototype.dispose.call(this);
  58909. };
  58910. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58911. if (!this._internalTextures) {
  58912. return;
  58913. }
  58914. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58915. if (this._internalTextures[i] !== undefined) {
  58916. this._internalTextures[i].dispose();
  58917. this._internalTextures.splice(i, 1);
  58918. }
  58919. }
  58920. };
  58921. return MultiRenderTarget;
  58922. }(BABYLON.RenderTargetTexture));
  58923. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58924. })(BABYLON || (BABYLON = {}));
  58925. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58926. "use strict";
  58927. var BABYLON;
  58928. (function (BABYLON) {
  58929. var MirrorTexture = /** @class */ (function (_super) {
  58930. __extends(MirrorTexture, _super);
  58931. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58932. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58933. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58934. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58935. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58936. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58937. _this._transformMatrix = BABYLON.Matrix.Zero();
  58938. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58939. _this._adaptiveBlurKernel = 0;
  58940. _this._blurKernelX = 0;
  58941. _this._blurKernelY = 0;
  58942. _this._blurRatio = 1.0;
  58943. _this.ignoreCameraViewport = true;
  58944. _this.onBeforeRenderObservable.add(function () {
  58945. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58946. _this._savedViewMatrix = scene.getViewMatrix();
  58947. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58948. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58949. scene.clipPlane = _this.mirrorPlane;
  58950. scene.getEngine().cullBackFaces = false;
  58951. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58952. });
  58953. _this.onAfterRenderObservable.add(function () {
  58954. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58955. scene.getEngine().cullBackFaces = true;
  58956. scene._mirroredCameraPosition = null;
  58957. delete scene.clipPlane;
  58958. });
  58959. return _this;
  58960. }
  58961. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58962. get: function () {
  58963. return this._blurRatio;
  58964. },
  58965. set: function (value) {
  58966. if (this._blurRatio === value) {
  58967. return;
  58968. }
  58969. this._blurRatio = value;
  58970. this._preparePostProcesses();
  58971. },
  58972. enumerable: true,
  58973. configurable: true
  58974. });
  58975. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58976. set: function (value) {
  58977. this._adaptiveBlurKernel = value;
  58978. this._autoComputeBlurKernel();
  58979. },
  58980. enumerable: true,
  58981. configurable: true
  58982. });
  58983. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58984. set: function (value) {
  58985. this.blurKernelX = value;
  58986. this.blurKernelY = value;
  58987. },
  58988. enumerable: true,
  58989. configurable: true
  58990. });
  58991. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58992. get: function () {
  58993. return this._blurKernelX;
  58994. },
  58995. set: function (value) {
  58996. if (this._blurKernelX === value) {
  58997. return;
  58998. }
  58999. this._blurKernelX = value;
  59000. this._preparePostProcesses();
  59001. },
  59002. enumerable: true,
  59003. configurable: true
  59004. });
  59005. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59006. get: function () {
  59007. return this._blurKernelY;
  59008. },
  59009. set: function (value) {
  59010. if (this._blurKernelY === value) {
  59011. return;
  59012. }
  59013. this._blurKernelY = value;
  59014. this._preparePostProcesses();
  59015. },
  59016. enumerable: true,
  59017. configurable: true
  59018. });
  59019. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59020. var engine = this.getScene().getEngine();
  59021. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59022. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59023. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59024. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59025. };
  59026. MirrorTexture.prototype._onRatioRescale = function () {
  59027. if (this._sizeRatio) {
  59028. this.resize(this._initialSizeParameter);
  59029. if (!this._adaptiveBlurKernel) {
  59030. this._preparePostProcesses();
  59031. }
  59032. }
  59033. if (this._adaptiveBlurKernel) {
  59034. this._autoComputeBlurKernel();
  59035. }
  59036. };
  59037. MirrorTexture.prototype._preparePostProcesses = function () {
  59038. this.clearPostProcesses(true);
  59039. if (this._blurKernelX && this._blurKernelY) {
  59040. var engine = this.getScene().getEngine();
  59041. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59042. 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);
  59043. this._blurX.autoClear = false;
  59044. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59045. this._blurX.inputTexture = this._texture;
  59046. }
  59047. else {
  59048. this._blurX.alwaysForcePOT = true;
  59049. }
  59050. 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);
  59051. this._blurY.autoClear = false;
  59052. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59053. this.addPostProcess(this._blurX);
  59054. this.addPostProcess(this._blurY);
  59055. }
  59056. else {
  59057. if (this._blurY) {
  59058. this.removePostProcess(this._blurY);
  59059. this._blurY.dispose();
  59060. this._blurY = null;
  59061. }
  59062. if (this._blurX) {
  59063. this.removePostProcess(this._blurX);
  59064. this._blurX.dispose();
  59065. this._blurX = null;
  59066. }
  59067. }
  59068. };
  59069. MirrorTexture.prototype.clone = function () {
  59070. var scene = this.getScene();
  59071. if (!scene) {
  59072. return this;
  59073. }
  59074. var textureSize = this.getSize();
  59075. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59076. // Base texture
  59077. newTexture.hasAlpha = this.hasAlpha;
  59078. newTexture.level = this.level;
  59079. // Mirror Texture
  59080. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59081. if (this.renderList) {
  59082. newTexture.renderList = this.renderList.slice(0);
  59083. }
  59084. return newTexture;
  59085. };
  59086. MirrorTexture.prototype.serialize = function () {
  59087. if (!this.name) {
  59088. return null;
  59089. }
  59090. var serializationObject = _super.prototype.serialize.call(this);
  59091. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59092. return serializationObject;
  59093. };
  59094. return MirrorTexture;
  59095. }(BABYLON.RenderTargetTexture));
  59096. BABYLON.MirrorTexture = MirrorTexture;
  59097. })(BABYLON || (BABYLON = {}));
  59098. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59099. "use strict";
  59100. var BABYLON;
  59101. (function (BABYLON) {
  59102. /**
  59103. * Creates a refraction texture used by refraction channel of the standard material.
  59104. * @param name the texture name
  59105. * @param size size of the underlying texture
  59106. * @param scene root scene
  59107. */
  59108. var RefractionTexture = /** @class */ (function (_super) {
  59109. __extends(RefractionTexture, _super);
  59110. function RefractionTexture(name, size, scene, generateMipMaps) {
  59111. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59112. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59113. _this.depth = 2.0;
  59114. _this.onBeforeRenderObservable.add(function () {
  59115. scene.clipPlane = _this.refractionPlane;
  59116. });
  59117. _this.onAfterRenderObservable.add(function () {
  59118. delete scene.clipPlane;
  59119. });
  59120. return _this;
  59121. }
  59122. RefractionTexture.prototype.clone = function () {
  59123. var scene = this.getScene();
  59124. if (!scene) {
  59125. return this;
  59126. }
  59127. var textureSize = this.getSize();
  59128. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59129. // Base texture
  59130. newTexture.hasAlpha = this.hasAlpha;
  59131. newTexture.level = this.level;
  59132. // Refraction Texture
  59133. newTexture.refractionPlane = this.refractionPlane.clone();
  59134. if (this.renderList) {
  59135. newTexture.renderList = this.renderList.slice(0);
  59136. }
  59137. newTexture.depth = this.depth;
  59138. return newTexture;
  59139. };
  59140. RefractionTexture.prototype.serialize = function () {
  59141. if (!this.name) {
  59142. return null;
  59143. }
  59144. var serializationObject = _super.prototype.serialize.call(this);
  59145. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59146. serializationObject.depth = this.depth;
  59147. return serializationObject;
  59148. };
  59149. return RefractionTexture;
  59150. }(BABYLON.RenderTargetTexture));
  59151. BABYLON.RefractionTexture = RefractionTexture;
  59152. })(BABYLON || (BABYLON = {}));
  59153. //# sourceMappingURL=babylon.refractionTexture.js.map
  59154. "use strict";
  59155. var BABYLON;
  59156. (function (BABYLON) {
  59157. var DynamicTexture = /** @class */ (function (_super) {
  59158. __extends(DynamicTexture, _super);
  59159. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59160. if (scene === void 0) { scene = null; }
  59161. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59162. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59163. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59164. _this.name = name;
  59165. _this._engine = _this.getScene().getEngine();
  59166. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59167. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59168. _this._generateMipMaps = generateMipMaps;
  59169. if (options.getContext) {
  59170. _this._canvas = options;
  59171. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59172. }
  59173. else {
  59174. _this._canvas = document.createElement("canvas");
  59175. if (options.width) {
  59176. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59177. }
  59178. else {
  59179. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59180. }
  59181. }
  59182. var textureSize = _this.getSize();
  59183. _this._canvas.width = textureSize.width;
  59184. _this._canvas.height = textureSize.height;
  59185. _this._context = _this._canvas.getContext("2d");
  59186. return _this;
  59187. }
  59188. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59189. get: function () {
  59190. return true;
  59191. },
  59192. enumerable: true,
  59193. configurable: true
  59194. });
  59195. DynamicTexture.prototype._recreate = function (textureSize) {
  59196. this._canvas.width = textureSize.width;
  59197. this._canvas.height = textureSize.height;
  59198. this.releaseInternalTexture();
  59199. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59200. };
  59201. DynamicTexture.prototype.scale = function (ratio) {
  59202. var textureSize = this.getSize();
  59203. textureSize.width *= ratio;
  59204. textureSize.height *= ratio;
  59205. this._recreate(textureSize);
  59206. };
  59207. DynamicTexture.prototype.scaleTo = function (width, height) {
  59208. var textureSize = this.getSize();
  59209. textureSize.width = width;
  59210. textureSize.height = height;
  59211. this._recreate(textureSize);
  59212. };
  59213. DynamicTexture.prototype.getContext = function () {
  59214. return this._context;
  59215. };
  59216. DynamicTexture.prototype.clear = function () {
  59217. var size = this.getSize();
  59218. this._context.fillRect(0, 0, size.width, size.height);
  59219. };
  59220. DynamicTexture.prototype.update = function (invertY) {
  59221. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59222. };
  59223. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59224. if (update === void 0) { update = true; }
  59225. var size = this.getSize();
  59226. if (clearColor) {
  59227. this._context.fillStyle = clearColor;
  59228. this._context.fillRect(0, 0, size.width, size.height);
  59229. }
  59230. this._context.font = font;
  59231. if (x === null || x === undefined) {
  59232. var textSize = this._context.measureText(text);
  59233. x = (size.width - textSize.width) / 2;
  59234. }
  59235. if (y === null || y === undefined) {
  59236. var fontSize = parseInt((font.replace(/\D/g, '')));
  59237. ;
  59238. y = (size.height / 2) + (fontSize / 3.65);
  59239. }
  59240. this._context.fillStyle = color;
  59241. this._context.fillText(text, x, y);
  59242. if (update) {
  59243. this.update(invertY);
  59244. }
  59245. };
  59246. DynamicTexture.prototype.clone = function () {
  59247. var scene = this.getScene();
  59248. if (!scene) {
  59249. return this;
  59250. }
  59251. var textureSize = this.getSize();
  59252. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59253. // Base texture
  59254. newTexture.hasAlpha = this.hasAlpha;
  59255. newTexture.level = this.level;
  59256. // Dynamic Texture
  59257. newTexture.wrapU = this.wrapU;
  59258. newTexture.wrapV = this.wrapV;
  59259. return newTexture;
  59260. };
  59261. DynamicTexture.prototype._rebuild = function () {
  59262. this.update();
  59263. };
  59264. return DynamicTexture;
  59265. }(BABYLON.Texture));
  59266. BABYLON.DynamicTexture = DynamicTexture;
  59267. })(BABYLON || (BABYLON = {}));
  59268. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59269. "use strict";
  59270. var BABYLON;
  59271. (function (BABYLON) {
  59272. var VideoTexture = /** @class */ (function (_super) {
  59273. __extends(VideoTexture, _super);
  59274. /**
  59275. * Creates a video texture.
  59276. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59277. * @param {string | null} name optional name, will detect from video source, if not defined
  59278. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59279. * @param {BABYLON.Scene} scene is obviously the current scene.
  59280. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59281. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59282. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59283. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59284. */
  59285. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59286. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59287. if (invertY === void 0) { invertY = false; }
  59288. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59289. if (settings === void 0) { settings = {
  59290. autoPlay: true,
  59291. loop: true,
  59292. autoUpdateTexture: true,
  59293. }; }
  59294. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59295. _this._createInternalTexture = function () {
  59296. if (_this._texture != null) {
  59297. return;
  59298. }
  59299. if (!_this._engine.needPOTTextures ||
  59300. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  59301. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59302. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59303. }
  59304. else {
  59305. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59306. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59307. _this._generateMipMaps = false;
  59308. }
  59309. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  59310. _this._texture.isReady = true;
  59311. _this._updateInternalTexture();
  59312. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  59313. _this.onLoadObservable.notifyObservers(_this);
  59314. }
  59315. };
  59316. _this.reset = function () {
  59317. if (_this._texture == null) {
  59318. return;
  59319. }
  59320. _this._texture.dispose();
  59321. _this._texture = null;
  59322. };
  59323. _this._updateInternalTexture = function (e) {
  59324. if (_this._texture == null || !_this._texture.isReady) {
  59325. return;
  59326. }
  59327. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  59328. return;
  59329. }
  59330. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  59331. };
  59332. _this._engine = _this.getScene().getEngine();
  59333. _this._generateMipMaps = generateMipMaps;
  59334. _this._samplingMode = samplingMode;
  59335. _this.autoUpdateTexture = settings.autoUpdateTexture;
  59336. _this.name = name || _this._getName(src);
  59337. _this.video = _this._getVideo(src);
  59338. if (settings.autoPlay !== undefined) {
  59339. _this.video.autoplay = settings.autoPlay;
  59340. }
  59341. if (settings.loop !== undefined) {
  59342. _this.video.loop = settings.loop;
  59343. }
  59344. _this.video.addEventListener("canplay", _this._createInternalTexture);
  59345. _this.video.addEventListener("paused", _this._updateInternalTexture);
  59346. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  59347. _this.video.addEventListener("emptied", _this.reset);
  59348. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  59349. _this._createInternalTexture();
  59350. }
  59351. return _this;
  59352. }
  59353. VideoTexture.prototype._getName = function (src) {
  59354. if (src instanceof HTMLVideoElement) {
  59355. return src.currentSrc;
  59356. }
  59357. if (typeof src === "object") {
  59358. return src.toString();
  59359. }
  59360. return src;
  59361. };
  59362. ;
  59363. VideoTexture.prototype._getVideo = function (src) {
  59364. if (src instanceof HTMLVideoElement) {
  59365. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  59366. return src;
  59367. }
  59368. var video = document.createElement("video");
  59369. if (typeof src === "string") {
  59370. BABYLON.Tools.SetCorsBehavior(src, video);
  59371. video.src = src;
  59372. }
  59373. else {
  59374. BABYLON.Tools.SetCorsBehavior(src[0], video);
  59375. src.forEach(function (url) {
  59376. var source = document.createElement("source");
  59377. source.src = url;
  59378. video.appendChild(source);
  59379. });
  59380. }
  59381. return video;
  59382. };
  59383. ;
  59384. /**
  59385. * Internal method to initiate `update`.
  59386. */
  59387. VideoTexture.prototype._rebuild = function () {
  59388. this.update();
  59389. };
  59390. /**
  59391. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  59392. */
  59393. VideoTexture.prototype.update = function () {
  59394. if (!this.autoUpdateTexture) {
  59395. // Expecting user to call `updateTexture` manually
  59396. return;
  59397. }
  59398. this.updateTexture(true);
  59399. };
  59400. /**
  59401. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  59402. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  59403. */
  59404. VideoTexture.prototype.updateTexture = function (isVisible) {
  59405. if (!isVisible) {
  59406. return;
  59407. }
  59408. if (this.video.paused) {
  59409. return;
  59410. }
  59411. this._updateInternalTexture();
  59412. };
  59413. /**
  59414. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  59415. * @param url New url.
  59416. */
  59417. VideoTexture.prototype.updateURL = function (url) {
  59418. this.video.src = url;
  59419. };
  59420. VideoTexture.prototype.dispose = function () {
  59421. _super.prototype.dispose.call(this);
  59422. this.video.removeEventListener("canplay", this._createInternalTexture);
  59423. this.video.removeEventListener("paused", this._updateInternalTexture);
  59424. this.video.removeEventListener("seeked", this._updateInternalTexture);
  59425. this.video.removeEventListener("emptied", this.reset);
  59426. this.video.pause();
  59427. };
  59428. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  59429. var video = document.createElement("video");
  59430. var constraintsDeviceId;
  59431. if (constraints && constraints.deviceId) {
  59432. constraintsDeviceId = {
  59433. exact: constraints.deviceId,
  59434. };
  59435. }
  59436. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  59437. if (navigator.mediaDevices) {
  59438. navigator.mediaDevices.getUserMedia({ video: constraints })
  59439. .then(function (stream) {
  59440. if (video.mozSrcObject !== undefined) {
  59441. // hack for Firefox < 19
  59442. video.mozSrcObject = stream;
  59443. }
  59444. else {
  59445. video.srcObject = stream;
  59446. }
  59447. var onPlaying = function () {
  59448. if (onReady) {
  59449. onReady(new VideoTexture("video", video, scene, true, true));
  59450. }
  59451. video.removeEventListener("playing", onPlaying);
  59452. };
  59453. video.addEventListener("playing", onPlaying);
  59454. video.play();
  59455. })
  59456. .catch(function (err) {
  59457. BABYLON.Tools.Error(err.name);
  59458. });
  59459. }
  59460. else {
  59461. navigator.getUserMedia =
  59462. navigator.getUserMedia ||
  59463. navigator.webkitGetUserMedia ||
  59464. navigator.mozGetUserMedia ||
  59465. navigator.msGetUserMedia;
  59466. if (navigator.getUserMedia) {
  59467. navigator.getUserMedia({
  59468. video: {
  59469. deviceId: constraintsDeviceId,
  59470. width: {
  59471. min: (constraints && constraints.minWidth) || 256,
  59472. max: (constraints && constraints.maxWidth) || 640,
  59473. },
  59474. height: {
  59475. min: (constraints && constraints.minHeight) || 256,
  59476. max: (constraints && constraints.maxHeight) || 480,
  59477. },
  59478. },
  59479. }, function (stream) {
  59480. if (video.mozSrcObject !== undefined) {
  59481. // hack for Firefox < 19
  59482. video.mozSrcObject = stream;
  59483. }
  59484. else {
  59485. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  59486. }
  59487. video.play();
  59488. if (onReady) {
  59489. onReady(new VideoTexture("video", video, scene, true, true));
  59490. }
  59491. }, function (e) {
  59492. BABYLON.Tools.Error(e.name);
  59493. });
  59494. }
  59495. }
  59496. };
  59497. return VideoTexture;
  59498. }(BABYLON.Texture));
  59499. BABYLON.VideoTexture = VideoTexture;
  59500. })(BABYLON || (BABYLON = {}));
  59501. //# sourceMappingURL=babylon.videoTexture.js.map
  59502. "use strict";
  59503. var BABYLON;
  59504. (function (BABYLON) {
  59505. var RawTexture = /** @class */ (function (_super) {
  59506. __extends(RawTexture, _super);
  59507. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  59508. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59509. if (invertY === void 0) { invertY = false; }
  59510. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59511. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59512. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59513. _this.format = format;
  59514. _this._engine = scene.getEngine();
  59515. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  59516. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59517. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59518. return _this;
  59519. }
  59520. RawTexture.prototype.update = function (data) {
  59521. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  59522. };
  59523. // Statics
  59524. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59525. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59526. if (invertY === void 0) { invertY = false; }
  59527. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59528. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  59529. };
  59530. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59531. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59532. if (invertY === void 0) { invertY = false; }
  59533. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59534. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59535. };
  59536. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  59537. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59538. if (invertY === void 0) { invertY = false; }
  59539. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59540. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  59541. };
  59542. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59543. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59544. if (invertY === void 0) { invertY = false; }
  59545. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59546. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59547. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  59548. };
  59549. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  59550. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59551. if (invertY === void 0) { invertY = false; }
  59552. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59553. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59554. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  59555. };
  59556. return RawTexture;
  59557. }(BABYLON.Texture));
  59558. BABYLON.RawTexture = RawTexture;
  59559. })(BABYLON || (BABYLON = {}));
  59560. //# sourceMappingURL=babylon.rawTexture.js.map
  59561. "use strict";
  59562. var BABYLON;
  59563. (function (BABYLON) {
  59564. /**
  59565. * PostProcess can be used to apply a shader to a texture after it has been rendered
  59566. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  59567. */
  59568. var PostProcess = /** @class */ (function () {
  59569. /**
  59570. * Creates a new instance of @see PostProcess
  59571. * @param name The name of the PostProcess.
  59572. * @param fragmentUrl The url of the fragment shader to be used.
  59573. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  59574. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  59575. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  59576. * @param camera The camera to apply the render pass to.
  59577. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  59578. * @param engine The engine which the post process will be applied. (default: current engine)
  59579. * @param reusable If the post process can be reused on the same frame. (default: false)
  59580. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  59581. * @param textureType Type of textures used when performing the post process. (default: 0)
  59582. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  59583. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  59584. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  59585. */
  59586. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  59587. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  59588. if (defines === void 0) { defines = null; }
  59589. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59590. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  59591. if (blockCompilation === void 0) { blockCompilation = false; }
  59592. this.name = name;
  59593. /**
  59594. * Width of the texture to apply the post process on
  59595. */
  59596. this.width = -1;
  59597. /**
  59598. * Height of the texture to apply the post process on
  59599. */
  59600. this.height = -1;
  59601. /**
  59602. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  59603. */
  59604. this._outputTexture = null;
  59605. /**
  59606. * If the buffer needs to be cleared before applying the post process. (default: true)
  59607. * Should be set to false if shader will overwrite all previous pixels.
  59608. */
  59609. this.autoClear = true;
  59610. /**
  59611. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  59612. */
  59613. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  59614. /**
  59615. * Animations to be used for the post processing
  59616. */
  59617. this.animations = new Array();
  59618. /**
  59619. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  59620. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  59621. */
  59622. this.enablePixelPerfectMode = false;
  59623. /**
  59624. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  59625. */
  59626. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  59627. /**
  59628. * Force textures to be a power of two (default: false)
  59629. */
  59630. this.alwaysForcePOT = false;
  59631. /**
  59632. * Number of sample textures (default: 1)
  59633. */
  59634. this.samples = 1;
  59635. /**
  59636. * Modify the scale of the post process to be the same as the viewport (default: false)
  59637. */
  59638. this.adaptScaleToCurrentViewport = false;
  59639. this._reusable = false;
  59640. /**
  59641. * Smart array of input and output textures for the post process.
  59642. */
  59643. this._textures = new BABYLON.SmartArray(2);
  59644. /**
  59645. * The index in _textures that corresponds to the output texture.
  59646. */
  59647. this._currentRenderTextureInd = 0;
  59648. this._scaleRatio = new BABYLON.Vector2(1, 1);
  59649. this._texelSize = BABYLON.Vector2.Zero();
  59650. // Events
  59651. /**
  59652. * An event triggered when the postprocess is activated.
  59653. * @type {BABYLON.Observable}
  59654. */
  59655. this.onActivateObservable = new BABYLON.Observable();
  59656. /**
  59657. * An event triggered when the postprocess changes its size.
  59658. * @type {BABYLON.Observable}
  59659. */
  59660. this.onSizeChangedObservable = new BABYLON.Observable();
  59661. /**
  59662. * An event triggered when the postprocess applies its effect.
  59663. * @type {BABYLON.Observable}
  59664. */
  59665. this.onApplyObservable = new BABYLON.Observable();
  59666. /**
  59667. * An event triggered before rendering the postprocess
  59668. * @type {BABYLON.Observable}
  59669. */
  59670. this.onBeforeRenderObservable = new BABYLON.Observable();
  59671. /**
  59672. * An event triggered after rendering the postprocess
  59673. * @type {BABYLON.Observable}
  59674. */
  59675. this.onAfterRenderObservable = new BABYLON.Observable();
  59676. if (camera != null) {
  59677. this._camera = camera;
  59678. this._scene = camera.getScene();
  59679. camera.attachPostProcess(this);
  59680. this._engine = this._scene.getEngine();
  59681. this._scene.postProcesses.push(this);
  59682. }
  59683. else if (engine) {
  59684. this._engine = engine;
  59685. this._engine.postProcesses.push(this);
  59686. }
  59687. this._options = options;
  59688. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  59689. this._reusable = reusable || false;
  59690. this._textureType = textureType;
  59691. this._samplers = samplers || [];
  59692. this._samplers.push("textureSampler");
  59693. this._fragmentUrl = fragmentUrl;
  59694. this._vertexUrl = vertexUrl;
  59695. this._parameters = parameters || [];
  59696. this._parameters.push("scale");
  59697. this._indexParameters = indexParameters;
  59698. if (!blockCompilation) {
  59699. this.updateEffect(defines);
  59700. }
  59701. }
  59702. Object.defineProperty(PostProcess.prototype, "onActivate", {
  59703. /**
  59704. * A function that is added to the onActivateObservable
  59705. */
  59706. set: function (callback) {
  59707. if (this._onActivateObserver) {
  59708. this.onActivateObservable.remove(this._onActivateObserver);
  59709. }
  59710. if (callback) {
  59711. this._onActivateObserver = this.onActivateObservable.add(callback);
  59712. }
  59713. },
  59714. enumerable: true,
  59715. configurable: true
  59716. });
  59717. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  59718. /**
  59719. * A function that is added to the onSizeChangedObservable
  59720. */
  59721. set: function (callback) {
  59722. if (this._onSizeChangedObserver) {
  59723. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  59724. }
  59725. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  59726. },
  59727. enumerable: true,
  59728. configurable: true
  59729. });
  59730. Object.defineProperty(PostProcess.prototype, "onApply", {
  59731. /**
  59732. * A function that is added to the onApplyObservable
  59733. */
  59734. set: function (callback) {
  59735. if (this._onApplyObserver) {
  59736. this.onApplyObservable.remove(this._onApplyObserver);
  59737. }
  59738. this._onApplyObserver = this.onApplyObservable.add(callback);
  59739. },
  59740. enumerable: true,
  59741. configurable: true
  59742. });
  59743. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  59744. /**
  59745. * A function that is added to the onBeforeRenderObservable
  59746. */
  59747. set: function (callback) {
  59748. if (this._onBeforeRenderObserver) {
  59749. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59750. }
  59751. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59752. },
  59753. enumerable: true,
  59754. configurable: true
  59755. });
  59756. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  59757. /**
  59758. * A function that is added to the onAfterRenderObservable
  59759. */
  59760. set: function (callback) {
  59761. if (this._onAfterRenderObserver) {
  59762. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59763. }
  59764. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59765. },
  59766. enumerable: true,
  59767. configurable: true
  59768. });
  59769. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  59770. /**
  59771. * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
  59772. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  59773. */
  59774. get: function () {
  59775. return this._textures.data[this._currentRenderTextureInd];
  59776. },
  59777. set: function (value) {
  59778. this._forcedOutputTexture = value;
  59779. },
  59780. enumerable: true,
  59781. configurable: true
  59782. });
  59783. /**
  59784. * Gets the camera which post process is applied to.
  59785. * @returns The camera the post process is applied to.
  59786. */
  59787. PostProcess.prototype.getCamera = function () {
  59788. return this._camera;
  59789. };
  59790. Object.defineProperty(PostProcess.prototype, "texelSize", {
  59791. /**
  59792. * Gets the texel size of the postprocess.
  59793. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  59794. */
  59795. get: function () {
  59796. if (this._shareOutputWithPostProcess) {
  59797. return this._shareOutputWithPostProcess.texelSize;
  59798. }
  59799. if (this._forcedOutputTexture) {
  59800. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  59801. }
  59802. return this._texelSize;
  59803. },
  59804. enumerable: true,
  59805. configurable: true
  59806. });
  59807. /**
  59808. * Gets the engine which this post process belongs to.
  59809. * @returns The engine the post process was enabled with.
  59810. */
  59811. PostProcess.prototype.getEngine = function () {
  59812. return this._engine;
  59813. };
  59814. /**
  59815. * The effect that is created when initializing the post process.
  59816. * @returns The created effect corrisponding the the postprocess.
  59817. */
  59818. PostProcess.prototype.getEffect = function () {
  59819. return this._effect;
  59820. };
  59821. /**
  59822. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  59823. * @param postProcess The post process to share the output with.
  59824. * @returns This post process.
  59825. */
  59826. PostProcess.prototype.shareOutputWith = function (postProcess) {
  59827. this._disposeTextures();
  59828. this._shareOutputWithPostProcess = postProcess;
  59829. return this;
  59830. };
  59831. /**
  59832. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  59833. * This should be called if the post process that shares output with this post process is disabled/disposed.
  59834. */
  59835. PostProcess.prototype.useOwnOutput = function () {
  59836. if (this._textures.length == 0) {
  59837. this._textures = new BABYLON.SmartArray(2);
  59838. }
  59839. this._shareOutputWithPostProcess = null;
  59840. };
  59841. /**
  59842. * Updates the effect with the current post process compile time values and recompiles the shader.
  59843. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  59844. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  59845. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  59846. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  59847. * @param onCompiled Called when the shader has been compiled.
  59848. * @param onError Called if there is an error when compiling a shader.
  59849. */
  59850. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  59851. if (defines === void 0) { defines = null; }
  59852. if (uniforms === void 0) { uniforms = null; }
  59853. if (samplers === void 0) { samplers = null; }
  59854. 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);
  59855. };
  59856. /**
  59857. * The post process is reusable if it can be used multiple times within one frame.
  59858. * @returns If the post process is reusable
  59859. */
  59860. PostProcess.prototype.isReusable = function () {
  59861. return this._reusable;
  59862. };
  59863. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  59864. PostProcess.prototype.markTextureDirty = function () {
  59865. this.width = -1;
  59866. };
  59867. /**
  59868. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  59869. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
  59870. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  59871. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  59872. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  59873. * @returns The target texture that was bound to be written to.
  59874. */
  59875. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  59876. var _this = this;
  59877. if (sourceTexture === void 0) { sourceTexture = null; }
  59878. camera = camera || this._camera;
  59879. var scene = camera.getScene();
  59880. var engine = scene.getEngine();
  59881. var maxSize = engine.getCaps().maxTextureSize;
  59882. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  59883. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  59884. // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
  59885. var webVRCamera = camera.parent;
  59886. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  59887. requiredWidth /= 2;
  59888. }
  59889. var desiredWidth = (this._options.width || requiredWidth);
  59890. var desiredHeight = this._options.height || requiredHeight;
  59891. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  59892. if (this.adaptScaleToCurrentViewport) {
  59893. var currentViewport = engine.currentViewport;
  59894. if (currentViewport) {
  59895. desiredWidth *= currentViewport.width;
  59896. desiredHeight *= currentViewport.height;
  59897. }
  59898. }
  59899. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59900. if (!this._options.width) {
  59901. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59902. }
  59903. if (!this._options.height) {
  59904. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59905. }
  59906. }
  59907. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59908. if (this._textures.length > 0) {
  59909. for (var i = 0; i < this._textures.length; i++) {
  59910. this._engine._releaseTexture(this._textures.data[i]);
  59911. }
  59912. this._textures.reset();
  59913. }
  59914. this.width = desiredWidth;
  59915. this.height = desiredHeight;
  59916. var textureSize = { width: this.width, height: this.height };
  59917. var textureOptions = {
  59918. generateMipMaps: false,
  59919. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59920. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59921. samplingMode: this.renderTargetSamplingMode,
  59922. type: this._textureType
  59923. };
  59924. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59925. if (this._reusable) {
  59926. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59927. }
  59928. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59929. this.onSizeChangedObservable.notifyObservers(this);
  59930. }
  59931. this._textures.forEach(function (texture) {
  59932. if (texture.samples !== _this.samples) {
  59933. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59934. }
  59935. });
  59936. }
  59937. var target;
  59938. if (this._shareOutputWithPostProcess) {
  59939. target = this._shareOutputWithPostProcess.inputTexture;
  59940. }
  59941. else if (this._forcedOutputTexture) {
  59942. target = this._forcedOutputTexture;
  59943. this.width = this._forcedOutputTexture.width;
  59944. this.height = this._forcedOutputTexture.height;
  59945. }
  59946. else {
  59947. target = this.inputTexture;
  59948. }
  59949. // Bind the input of this post process to be used as the output of the previous post process.
  59950. if (this.enablePixelPerfectMode) {
  59951. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59952. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59953. }
  59954. else {
  59955. this._scaleRatio.copyFromFloats(1, 1);
  59956. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59957. }
  59958. this.onActivateObservable.notifyObservers(camera);
  59959. // Clear
  59960. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59961. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59962. }
  59963. if (this._reusable) {
  59964. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59965. }
  59966. return target;
  59967. };
  59968. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59969. /**
  59970. * If the post process is supported.
  59971. */
  59972. get: function () {
  59973. return this._effect.isSupported;
  59974. },
  59975. enumerable: true,
  59976. configurable: true
  59977. });
  59978. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59979. /**
  59980. * The aspect ratio of the output texture.
  59981. */
  59982. get: function () {
  59983. if (this._shareOutputWithPostProcess) {
  59984. return this._shareOutputWithPostProcess.aspectRatio;
  59985. }
  59986. if (this._forcedOutputTexture) {
  59987. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59988. }
  59989. return this.width / this.height;
  59990. },
  59991. enumerable: true,
  59992. configurable: true
  59993. });
  59994. /**
  59995. * Get a value indicating if the post-process is ready to be used
  59996. * @returns true if the post-process is ready (shader is compiled)
  59997. */
  59998. PostProcess.prototype.isReady = function () {
  59999. return this._effect && this._effect.isReady();
  60000. };
  60001. /**
  60002. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60003. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60004. */
  60005. PostProcess.prototype.apply = function () {
  60006. // Check
  60007. if (!this._effect || !this._effect.isReady())
  60008. return null;
  60009. // States
  60010. this._engine.enableEffect(this._effect);
  60011. this._engine.setState(false);
  60012. this._engine.setDepthBuffer(false);
  60013. this._engine.setDepthWrite(false);
  60014. // Alpha
  60015. this._engine.setAlphaMode(this.alphaMode);
  60016. if (this.alphaConstants) {
  60017. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60018. }
  60019. // Bind the output texture of the preivous post process as the input to this post process.
  60020. var source;
  60021. if (this._shareOutputWithPostProcess) {
  60022. source = this._shareOutputWithPostProcess.inputTexture;
  60023. }
  60024. else if (this._forcedOutputTexture) {
  60025. source = this._forcedOutputTexture;
  60026. }
  60027. else {
  60028. source = this.inputTexture;
  60029. }
  60030. this._effect._bindTexture("textureSampler", source);
  60031. // Parameters
  60032. this._effect.setVector2("scale", this._scaleRatio);
  60033. this.onApplyObservable.notifyObservers(this._effect);
  60034. return this._effect;
  60035. };
  60036. PostProcess.prototype._disposeTextures = function () {
  60037. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60038. return;
  60039. }
  60040. if (this._textures.length > 0) {
  60041. for (var i = 0; i < this._textures.length; i++) {
  60042. this._engine._releaseTexture(this._textures.data[i]);
  60043. }
  60044. }
  60045. this._textures.dispose();
  60046. };
  60047. /**
  60048. * Disposes the post process.
  60049. * @param camera The camera to dispose the post process on.
  60050. */
  60051. PostProcess.prototype.dispose = function (camera) {
  60052. camera = camera || this._camera;
  60053. this._disposeTextures();
  60054. if (this._scene) {
  60055. var index_1 = this._scene.postProcesses.indexOf(this);
  60056. if (index_1 !== -1) {
  60057. this._scene.postProcesses.splice(index_1, 1);
  60058. }
  60059. }
  60060. else {
  60061. var index_2 = this._engine.postProcesses.indexOf(this);
  60062. if (index_2 !== -1) {
  60063. this._engine.postProcesses.splice(index_2, 1);
  60064. }
  60065. }
  60066. if (!camera) {
  60067. return;
  60068. }
  60069. camera.detachPostProcess(this);
  60070. var index = camera._postProcesses.indexOf(this);
  60071. if (index === 0 && camera._postProcesses.length > 0) {
  60072. var firstPostProcess = this._camera._getFirstPostProcess();
  60073. if (firstPostProcess) {
  60074. firstPostProcess.markTextureDirty();
  60075. }
  60076. }
  60077. this.onActivateObservable.clear();
  60078. this.onAfterRenderObservable.clear();
  60079. this.onApplyObservable.clear();
  60080. this.onBeforeRenderObservable.clear();
  60081. this.onSizeChangedObservable.clear();
  60082. };
  60083. return PostProcess;
  60084. }());
  60085. BABYLON.PostProcess = PostProcess;
  60086. })(BABYLON || (BABYLON = {}));
  60087. //# sourceMappingURL=babylon.postProcess.js.map
  60088. "use strict";
  60089. var BABYLON;
  60090. (function (BABYLON) {
  60091. var PassPostProcess = /** @class */ (function (_super) {
  60092. __extends(PassPostProcess, _super);
  60093. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60094. if (camera === void 0) { camera = null; }
  60095. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60096. if (blockCompilation === void 0) { blockCompilation = false; }
  60097. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60098. }
  60099. return PassPostProcess;
  60100. }(BABYLON.PostProcess));
  60101. BABYLON.PassPostProcess = PassPostProcess;
  60102. })(BABYLON || (BABYLON = {}));
  60103. //# sourceMappingURL=babylon.passPostProcess.js.map
  60104. "use strict";
  60105. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60106. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60107. s = arguments[i];
  60108. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60109. t[p] = s[p];
  60110. }
  60111. return t;
  60112. };
  60113. var BABYLON;
  60114. (function (BABYLON) {
  60115. /**
  60116. * Default implementation of @see IShadowGenerator.
  60117. * This is the main object responsible of generating shadows in the framework.
  60118. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60119. */
  60120. var ShadowGenerator = /** @class */ (function () {
  60121. /**
  60122. * Creates a ShadowGenerator object.
  60123. * A ShadowGenerator is the required tool to use the shadows.
  60124. * Each light casting shadows needs to use its own ShadowGenerator.
  60125. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60126. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60127. * @param light The light object generating the shadows.
  60128. * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  60129. */
  60130. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60131. this._bias = 0.00005;
  60132. this._normalBias = 0;
  60133. this._blurBoxOffset = 1;
  60134. this._blurScale = 2;
  60135. this._blurKernel = 1;
  60136. this._useKernelBlur = false;
  60137. this._filter = ShadowGenerator.FILTER_NONE;
  60138. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  60139. this._contactHardeningLightSizeUVRatio = 0.1;
  60140. this._darkness = 0;
  60141. this._transparencyShadow = false;
  60142. /**
  60143. * Controls the extent to which the shadows fade out at the edge of the frustum
  60144. * Used only by directionals and spots
  60145. */
  60146. this.frustumEdgeFalloff = 0;
  60147. /**
  60148. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60149. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60150. * It might on the other hand introduce peter panning.
  60151. */
  60152. this.forceBackFacesOnly = false;
  60153. this._lightDirection = BABYLON.Vector3.Zero();
  60154. this._viewMatrix = BABYLON.Matrix.Zero();
  60155. this._projectionMatrix = BABYLON.Matrix.Zero();
  60156. this._transformMatrix = BABYLON.Matrix.Zero();
  60157. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60158. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60159. this._currentFaceIndex = 0;
  60160. this._currentFaceIndexCache = 0;
  60161. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60162. this._mapSize = mapSize;
  60163. this._light = light;
  60164. this._scene = light.getScene();
  60165. light._shadowGenerator = this;
  60166. // Texture type fallback from float to int if not supported.
  60167. var caps = this._scene.getEngine().getCaps();
  60168. if (!useFullFloatFirst) {
  60169. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60170. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60171. }
  60172. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60173. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60174. }
  60175. else {
  60176. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60177. }
  60178. }
  60179. else {
  60180. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60181. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60182. }
  60183. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60184. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60185. }
  60186. else {
  60187. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60188. }
  60189. }
  60190. this._initializeGenerator();
  60191. this._applyFilterValues();
  60192. }
  60193. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60194. /**
  60195. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  60196. */
  60197. get: function () {
  60198. return this._bias;
  60199. },
  60200. /**
  60201. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  60202. */
  60203. set: function (bias) {
  60204. this._bias = bias;
  60205. },
  60206. enumerable: true,
  60207. configurable: true
  60208. });
  60209. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  60210. /**
  60211. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60212. */
  60213. get: function () {
  60214. return this._normalBias;
  60215. },
  60216. /**
  60217. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60218. */
  60219. set: function (normalBias) {
  60220. this._normalBias = normalBias;
  60221. },
  60222. enumerable: true,
  60223. configurable: true
  60224. });
  60225. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60226. /**
  60227. * Gets the blur box offset: offset applied during the blur pass.
  60228. * Only usefull if useKernelBlur = false
  60229. */
  60230. get: function () {
  60231. return this._blurBoxOffset;
  60232. },
  60233. /**
  60234. * Sets the blur box offset: offset applied during the blur pass.
  60235. * Only usefull if useKernelBlur = false
  60236. */
  60237. set: function (value) {
  60238. if (this._blurBoxOffset === value) {
  60239. return;
  60240. }
  60241. this._blurBoxOffset = value;
  60242. this._disposeBlurPostProcesses();
  60243. },
  60244. enumerable: true,
  60245. configurable: true
  60246. });
  60247. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60248. /**
  60249. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60250. * 2 means half of the size.
  60251. */
  60252. get: function () {
  60253. return this._blurScale;
  60254. },
  60255. /**
  60256. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60257. * 2 means half of the size.
  60258. */
  60259. set: function (value) {
  60260. if (this._blurScale === value) {
  60261. return;
  60262. }
  60263. this._blurScale = value;
  60264. this._disposeBlurPostProcesses();
  60265. },
  60266. enumerable: true,
  60267. configurable: true
  60268. });
  60269. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60270. /**
  60271. * Gets the blur kernel: kernel size of the blur pass.
  60272. * Only usefull if useKernelBlur = true
  60273. */
  60274. get: function () {
  60275. return this._blurKernel;
  60276. },
  60277. /**
  60278. * Sets the blur kernel: kernel size of the blur pass.
  60279. * Only usefull if useKernelBlur = true
  60280. */
  60281. set: function (value) {
  60282. if (this._blurKernel === value) {
  60283. return;
  60284. }
  60285. this._blurKernel = value;
  60286. this._disposeBlurPostProcesses();
  60287. },
  60288. enumerable: true,
  60289. configurable: true
  60290. });
  60291. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60292. /**
  60293. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60294. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60295. */
  60296. get: function () {
  60297. return this._useKernelBlur;
  60298. },
  60299. /**
  60300. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  60301. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60302. */
  60303. set: function (value) {
  60304. if (this._useKernelBlur === value) {
  60305. return;
  60306. }
  60307. this._useKernelBlur = value;
  60308. this._disposeBlurPostProcesses();
  60309. },
  60310. enumerable: true,
  60311. configurable: true
  60312. });
  60313. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  60314. /**
  60315. * Gets the depth scale used in ESM mode.
  60316. */
  60317. get: function () {
  60318. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  60319. },
  60320. /**
  60321. * Sets the depth scale used in ESM mode.
  60322. * This can override the scale stored on the light.
  60323. */
  60324. set: function (value) {
  60325. this._depthScale = value;
  60326. },
  60327. enumerable: true,
  60328. configurable: true
  60329. });
  60330. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  60331. /**
  60332. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  60333. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60334. */
  60335. get: function () {
  60336. return this._filter;
  60337. },
  60338. /**
  60339. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  60340. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  60341. */
  60342. set: function (value) {
  60343. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  60344. if (this._light.needCube()) {
  60345. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60346. this.useExponentialShadowMap = true;
  60347. return;
  60348. }
  60349. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60350. this.useCloseExponentialShadowMap = true;
  60351. return;
  60352. }
  60353. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  60354. this.usePoissonSampling = true;
  60355. return;
  60356. }
  60357. }
  60358. // Weblg1 fallback for PCF.
  60359. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  60360. if (this._scene.getEngine().webGLVersion === 1) {
  60361. this.usePoissonSampling = true;
  60362. return;
  60363. }
  60364. }
  60365. if (this._filter === value) {
  60366. return;
  60367. }
  60368. this._filter = value;
  60369. this._disposeBlurPostProcesses();
  60370. this._applyFilterValues();
  60371. this._light._markMeshesAsLightDirty();
  60372. },
  60373. enumerable: true,
  60374. configurable: true
  60375. });
  60376. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  60377. /**
  60378. * Gets if the current filter is set to Poisson Sampling.
  60379. */
  60380. get: function () {
  60381. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  60382. },
  60383. /**
  60384. * Sets the current filter to Poisson Sampling.
  60385. */
  60386. set: function (value) {
  60387. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  60388. return;
  60389. }
  60390. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  60391. },
  60392. enumerable: true,
  60393. configurable: true
  60394. });
  60395. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  60396. /**
  60397. * Gets if the current filter is set to VSM.
  60398. * DEPRECATED. Should use useExponentialShadowMap instead.
  60399. */
  60400. get: function () {
  60401. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60402. return this.useExponentialShadowMap;
  60403. },
  60404. /**
  60405. * Sets the current filter is to VSM.
  60406. * DEPRECATED. Should use useExponentialShadowMap instead.
  60407. */
  60408. set: function (value) {
  60409. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  60410. this.useExponentialShadowMap = value;
  60411. },
  60412. enumerable: true,
  60413. configurable: true
  60414. });
  60415. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  60416. /**
  60417. * Gets if the current filter is set to blurred VSM.
  60418. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60419. */
  60420. get: function () {
  60421. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60422. return this.useBlurExponentialShadowMap;
  60423. },
  60424. /**
  60425. * Sets the current filter is to blurred VSM.
  60426. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  60427. */
  60428. set: function (value) {
  60429. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  60430. this.useBlurExponentialShadowMap = value;
  60431. },
  60432. enumerable: true,
  60433. configurable: true
  60434. });
  60435. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  60436. /**
  60437. * Gets if the current filter is set to ESM.
  60438. */
  60439. get: function () {
  60440. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  60441. },
  60442. /**
  60443. * Sets the current filter is to ESM.
  60444. */
  60445. set: function (value) {
  60446. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  60447. return;
  60448. }
  60449. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60450. },
  60451. enumerable: true,
  60452. configurable: true
  60453. });
  60454. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  60455. /**
  60456. * Gets if the current filter is set to filtered ESM.
  60457. */
  60458. get: function () {
  60459. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  60460. },
  60461. /**
  60462. * Gets if the current filter is set to filtered ESM.
  60463. */
  60464. set: function (value) {
  60465. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  60466. return;
  60467. }
  60468. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60469. },
  60470. enumerable: true,
  60471. configurable: true
  60472. });
  60473. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  60474. /**
  60475. * Gets if the current filter is set to "close ESM" (using the inverse of the
  60476. * exponential to prevent steep falloff artifacts).
  60477. */
  60478. get: function () {
  60479. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  60480. },
  60481. /**
  60482. * Sets the current filter to "close ESM" (using the inverse of the
  60483. * exponential to prevent steep falloff artifacts).
  60484. */
  60485. set: function (value) {
  60486. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  60487. return;
  60488. }
  60489. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60490. },
  60491. enumerable: true,
  60492. configurable: true
  60493. });
  60494. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  60495. /**
  60496. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  60497. * exponential to prevent steep falloff artifacts).
  60498. */
  60499. get: function () {
  60500. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  60501. },
  60502. /**
  60503. * Sets the current filter to filtered "close ESM" (using the inverse of the
  60504. * exponential to prevent steep falloff artifacts).
  60505. */
  60506. set: function (value) {
  60507. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  60508. return;
  60509. }
  60510. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  60511. },
  60512. enumerable: true,
  60513. configurable: true
  60514. });
  60515. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  60516. /**
  60517. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  60518. */
  60519. get: function () {
  60520. return this.filter === ShadowGenerator.FILTER_PCF;
  60521. },
  60522. /**
  60523. * Sets the current filter to "PCF" (percentage closer filtering).
  60524. */
  60525. set: function (value) {
  60526. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  60527. return;
  60528. }
  60529. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  60530. },
  60531. enumerable: true,
  60532. configurable: true
  60533. });
  60534. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  60535. /**
  60536. * Gets the PCF or PCSS Quality.
  60537. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  60538. */
  60539. get: function () {
  60540. return this._filteringQuality;
  60541. },
  60542. /**
  60543. * Sets the PCF or PCSS Quality.
  60544. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  60545. */
  60546. set: function (filteringQuality) {
  60547. this._filteringQuality = filteringQuality;
  60548. },
  60549. enumerable: true,
  60550. configurable: true
  60551. });
  60552. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  60553. /**
  60554. * Gets if the current filter is set to "PCSS" (contact hardening).
  60555. */
  60556. get: function () {
  60557. return this.filter === ShadowGenerator.FILTER_PCSS;
  60558. },
  60559. /**
  60560. * Sets the current filter to "PCSS" (contact hardening).
  60561. */
  60562. set: function (value) {
  60563. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  60564. return;
  60565. }
  60566. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  60567. },
  60568. enumerable: true,
  60569. configurable: true
  60570. });
  60571. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  60572. /**
  60573. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  60574. * Using a ratio helps keeping shape stability independently of the map size.
  60575. *
  60576. * It does not account for the light projection as it was having too much
  60577. * instability during the light setup or during light position changes.
  60578. *
  60579. * Only valid if useContactHardeningShadow is true.
  60580. */
  60581. get: function () {
  60582. return this._contactHardeningLightSizeUVRatio;
  60583. },
  60584. /**
  60585. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  60586. * Using a ratio helps keeping shape stability independently of the map size.
  60587. *
  60588. * It does not account for the light projection as it was having too much
  60589. * instability during the light setup or during light position changes.
  60590. *
  60591. * Only valid if useContactHardeningShadow is true.
  60592. */
  60593. set: function (contactHardeningLightSizeUVRatio) {
  60594. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  60595. },
  60596. enumerable: true,
  60597. configurable: true
  60598. });
  60599. /**
  60600. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  60601. * 0 means strongest and 1 would means no shadow.
  60602. * @returns the darkness.
  60603. */
  60604. ShadowGenerator.prototype.getDarkness = function () {
  60605. return this._darkness;
  60606. };
  60607. /**
  60608. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  60609. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  60610. * @returns the shadow generator allowing fluent coding.
  60611. */
  60612. ShadowGenerator.prototype.setDarkness = function (darkness) {
  60613. if (darkness >= 1.0)
  60614. this._darkness = 1.0;
  60615. else if (darkness <= 0.0)
  60616. this._darkness = 0.0;
  60617. else
  60618. this._darkness = darkness;
  60619. return this;
  60620. };
  60621. /**
  60622. * Sets the ability to have transparent shadow (boolean).
  60623. * @param transparent True if transparent else False
  60624. * @returns the shadow generator allowing fluent coding
  60625. */
  60626. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  60627. this._transparencyShadow = transparent;
  60628. return this;
  60629. };
  60630. /**
  60631. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  60632. * @returns The render target texture if present otherwise, null
  60633. */
  60634. ShadowGenerator.prototype.getShadowMap = function () {
  60635. return this._shadowMap;
  60636. };
  60637. /**
  60638. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  60639. * @returns The render target texture if the shadow map is present otherwise, null
  60640. */
  60641. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  60642. if (this._shadowMap2) {
  60643. return this._shadowMap2;
  60644. }
  60645. return this._shadowMap;
  60646. };
  60647. /**
  60648. * Helper function to add a mesh and its descendants to the list of shadow casters.
  60649. * @param mesh Mesh to add
  60650. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  60651. * @returns the Shadow Generator itself
  60652. */
  60653. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  60654. if (includeDescendants === void 0) { includeDescendants = true; }
  60655. if (!this._shadowMap) {
  60656. return this;
  60657. }
  60658. if (!this._shadowMap.renderList) {
  60659. this._shadowMap.renderList = [];
  60660. }
  60661. this._shadowMap.renderList.push(mesh);
  60662. if (includeDescendants) {
  60663. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  60664. }
  60665. return this;
  60666. var _a;
  60667. };
  60668. /**
  60669. * Helper function to remove a mesh and its descendants from the list of shadow casters
  60670. * @param mesh Mesh to remove
  60671. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  60672. * @returns the Shadow Generator itself
  60673. */
  60674. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  60675. if (includeDescendants === void 0) { includeDescendants = true; }
  60676. if (!this._shadowMap || !this._shadowMap.renderList) {
  60677. return this;
  60678. }
  60679. var index = this._shadowMap.renderList.indexOf(mesh);
  60680. if (index !== -1) {
  60681. this._shadowMap.renderList.splice(index, 1);
  60682. }
  60683. if (includeDescendants) {
  60684. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  60685. var child = _a[_i];
  60686. this.removeShadowCaster(child);
  60687. }
  60688. }
  60689. return this;
  60690. };
  60691. /**
  60692. * Returns the associated light object.
  60693. * @returns the light generating the shadow
  60694. */
  60695. ShadowGenerator.prototype.getLight = function () {
  60696. return this._light;
  60697. };
  60698. ShadowGenerator.prototype._initializeGenerator = function () {
  60699. this._light._markMeshesAsLightDirty();
  60700. this._initializeShadowMap();
  60701. };
  60702. ShadowGenerator.prototype._initializeShadowMap = function () {
  60703. var _this = this;
  60704. // Render target
  60705. var engine = this._scene.getEngine();
  60706. if (engine.webGLVersion > 1) {
  60707. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  60708. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  60709. }
  60710. else {
  60711. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  60712. }
  60713. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60714. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60715. this._shadowMap.anisotropicFilteringLevel = 1;
  60716. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60717. this._shadowMap.renderParticles = false;
  60718. this._shadowMap.ignoreCameraViewport = true;
  60719. // Record Face Index before render.
  60720. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  60721. _this._currentFaceIndex = faceIndex;
  60722. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  60723. engine.setColorWrite(false);
  60724. }
  60725. });
  60726. // Custom render function.
  60727. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  60728. // Blur if required afer render.
  60729. this._shadowMap.onAfterUnbindObservable.add(function () {
  60730. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  60731. engine.setColorWrite(true);
  60732. }
  60733. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  60734. return;
  60735. }
  60736. var shadowMap = _this.getShadowMapForRendering();
  60737. if (shadowMap) {
  60738. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  60739. }
  60740. });
  60741. // Clear according to the chosen filter.
  60742. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  60743. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  60744. this._shadowMap.onClearObservable.add(function (engine) {
  60745. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  60746. engine.clear(clearOne, false, true, false);
  60747. }
  60748. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  60749. engine.clear(clearZero, true, true, false);
  60750. }
  60751. else {
  60752. engine.clear(clearOne, true, true, false);
  60753. }
  60754. });
  60755. };
  60756. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  60757. var _this = this;
  60758. var engine = this._scene.getEngine();
  60759. var targetSize = this._mapSize / this.blurScale;
  60760. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  60761. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  60762. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60763. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60764. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60765. }
  60766. if (this.useKernelBlur) {
  60767. 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);
  60768. this._kernelBlurXPostprocess.width = targetSize;
  60769. this._kernelBlurXPostprocess.height = targetSize;
  60770. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  60771. effect.setTexture("textureSampler", _this._shadowMap);
  60772. });
  60773. 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);
  60774. this._kernelBlurXPostprocess.autoClear = false;
  60775. this._kernelBlurYPostprocess.autoClear = false;
  60776. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60777. this._kernelBlurXPostprocess.packedFloat = true;
  60778. this._kernelBlurYPostprocess.packedFloat = true;
  60779. }
  60780. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  60781. }
  60782. else {
  60783. 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);
  60784. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  60785. effect.setFloat2("screenSize", targetSize, targetSize);
  60786. effect.setTexture("textureSampler", _this._shadowMap);
  60787. });
  60788. this._boxBlurPostprocess.autoClear = false;
  60789. this._blurPostProcesses = [this._boxBlurPostprocess];
  60790. }
  60791. };
  60792. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  60793. var index;
  60794. var engine = this._scene.getEngine();
  60795. if (depthOnlySubMeshes.length) {
  60796. engine.setColorWrite(false);
  60797. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  60798. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  60799. }
  60800. engine.setColorWrite(true);
  60801. }
  60802. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60803. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  60804. }
  60805. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60806. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  60807. }
  60808. if (this._transparencyShadow) {
  60809. for (index = 0; index < transparentSubMeshes.length; index++) {
  60810. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  60811. }
  60812. }
  60813. };
  60814. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  60815. var _this = this;
  60816. var mesh = subMesh.getRenderingMesh();
  60817. var scene = this._scene;
  60818. var engine = scene.getEngine();
  60819. var material = subMesh.getMaterial();
  60820. if (!material) {
  60821. return;
  60822. }
  60823. // Culling
  60824. engine.setState(material.backFaceCulling);
  60825. // Managing instances
  60826. var batch = mesh._getInstancesRenderList(subMesh._id);
  60827. if (batch.mustReturn) {
  60828. return;
  60829. }
  60830. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60831. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  60832. engine.enableEffect(this._effect);
  60833. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60834. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  60835. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  60836. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  60837. this._effect.setVector3("lightData", this._cachedDirection);
  60838. }
  60839. else {
  60840. this._effect.setVector3("lightData", this._cachedPosition);
  60841. }
  60842. if (scene.activeCamera) {
  60843. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  60844. }
  60845. // Alpha test
  60846. if (material && material.needAlphaTesting()) {
  60847. var alphaTexture = material.getAlphaTestTexture();
  60848. if (alphaTexture) {
  60849. this._effect.setTexture("diffuseSampler", alphaTexture);
  60850. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  60851. }
  60852. }
  60853. // Bones
  60854. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60855. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  60856. }
  60857. if (this.forceBackFacesOnly) {
  60858. engine.setState(true, 0, false, true);
  60859. }
  60860. // Draw
  60861. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  60862. if (this.forceBackFacesOnly) {
  60863. engine.setState(true, 0, false, false);
  60864. }
  60865. }
  60866. else {
  60867. // Need to reset refresh rate of the shadowMap
  60868. if (this._shadowMap) {
  60869. this._shadowMap.resetRefreshCounter();
  60870. }
  60871. }
  60872. };
  60873. ShadowGenerator.prototype._applyFilterValues = function () {
  60874. if (!this._shadowMap) {
  60875. return;
  60876. }
  60877. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  60878. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  60879. }
  60880. else {
  60881. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60882. }
  60883. };
  60884. /**
  60885. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60886. * @param onCompiled Callback triggered at the and of the effects compilation
  60887. * @param options Sets of optional options forcing the compilation with different modes
  60888. */
  60889. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  60890. var _this = this;
  60891. var localOptions = __assign({ useInstances: false }, options);
  60892. var shadowMap = this.getShadowMap();
  60893. if (!shadowMap) {
  60894. if (onCompiled) {
  60895. onCompiled(this);
  60896. }
  60897. return;
  60898. }
  60899. var renderList = shadowMap.renderList;
  60900. if (!renderList) {
  60901. if (onCompiled) {
  60902. onCompiled(this);
  60903. }
  60904. return;
  60905. }
  60906. var subMeshes = new Array();
  60907. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  60908. var mesh = renderList_1[_i];
  60909. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  60910. }
  60911. if (subMeshes.length === 0) {
  60912. if (onCompiled) {
  60913. onCompiled(this);
  60914. }
  60915. return;
  60916. }
  60917. var currentIndex = 0;
  60918. var checkReady = function () {
  60919. if (!_this._scene || !_this._scene.getEngine()) {
  60920. return;
  60921. }
  60922. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  60923. currentIndex++;
  60924. if (currentIndex >= subMeshes.length) {
  60925. if (onCompiled) {
  60926. onCompiled(_this);
  60927. }
  60928. return;
  60929. }
  60930. }
  60931. setTimeout(checkReady, 16);
  60932. };
  60933. checkReady();
  60934. };
  60935. /**
  60936. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  60937. * @param options Sets of optional options forcing the compilation with different modes
  60938. * @returns A promise that resolves when the compilation completes
  60939. */
  60940. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  60941. var _this = this;
  60942. return new Promise(function (resolve) {
  60943. _this.forceCompilation(function () {
  60944. resolve();
  60945. }, options);
  60946. });
  60947. };
  60948. /**
  60949. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  60950. * @param subMesh The submesh we want to render in the shadow map
  60951. * @param useInstances Defines wether will draw in the map using instances
  60952. * @returns true if ready otherwise, false
  60953. */
  60954. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  60955. var defines = [];
  60956. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  60957. defines.push("#define FLOAT");
  60958. }
  60959. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60960. defines.push("#define ESM");
  60961. }
  60962. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  60963. defines.push("#define DEPTHTEXTURE");
  60964. }
  60965. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60966. var mesh = subMesh.getMesh();
  60967. var material = subMesh.getMaterial();
  60968. // Normal bias.
  60969. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  60970. attribs.push(BABYLON.VertexBuffer.NormalKind);
  60971. defines.push("#define NORMAL");
  60972. if (mesh.nonUniformScaling) {
  60973. defines.push("#define NONUNIFORMSCALING");
  60974. }
  60975. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  60976. defines.push("#define DIRECTIONINLIGHTDATA");
  60977. }
  60978. }
  60979. // Alpha test
  60980. if (material && material.needAlphaTesting()) {
  60981. var alphaTexture = material.getAlphaTestTexture();
  60982. if (alphaTexture) {
  60983. defines.push("#define ALPHATEST");
  60984. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60985. attribs.push(BABYLON.VertexBuffer.UVKind);
  60986. defines.push("#define UV1");
  60987. }
  60988. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60989. if (alphaTexture.coordinatesIndex === 1) {
  60990. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60991. defines.push("#define UV2");
  60992. }
  60993. }
  60994. }
  60995. }
  60996. // Bones
  60997. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60998. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60999. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61000. if (mesh.numBoneInfluencers > 4) {
  61001. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61002. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61003. }
  61004. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61005. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61006. }
  61007. else {
  61008. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61009. }
  61010. // Instances
  61011. if (useInstances) {
  61012. defines.push("#define INSTANCES");
  61013. attribs.push("world0");
  61014. attribs.push("world1");
  61015. attribs.push("world2");
  61016. attribs.push("world3");
  61017. }
  61018. // Get correct effect
  61019. var join = defines.join("\n");
  61020. if (this._cachedDefines !== join) {
  61021. this._cachedDefines = join;
  61022. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  61023. }
  61024. if (!this._effect.isReady()) {
  61025. return false;
  61026. }
  61027. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61028. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61029. this._initializeBlurRTTAndPostProcesses();
  61030. }
  61031. }
  61032. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61033. return false;
  61034. }
  61035. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61036. return false;
  61037. }
  61038. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61039. return false;
  61040. }
  61041. return true;
  61042. };
  61043. /**
  61044. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61045. * @param defines Defines of the material we want to update
  61046. * @param lightIndex Index of the light in the enabled light list of the material
  61047. */
  61048. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61049. var scene = this._scene;
  61050. var light = this._light;
  61051. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61052. return;
  61053. }
  61054. defines["SHADOW" + lightIndex] = true;
  61055. if (this.useContactHardeningShadow) {
  61056. defines["SHADOWPCSS" + lightIndex] = true;
  61057. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61058. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61059. }
  61060. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61061. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61062. }
  61063. // else default to high.
  61064. }
  61065. if (this.usePercentageCloserFiltering) {
  61066. defines["SHADOWPCF" + lightIndex] = true;
  61067. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61068. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61069. }
  61070. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61071. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61072. }
  61073. // else default to high.
  61074. }
  61075. else if (this.usePoissonSampling) {
  61076. defines["SHADOWPOISSON" + lightIndex] = true;
  61077. }
  61078. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61079. defines["SHADOWESM" + lightIndex] = true;
  61080. }
  61081. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61082. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61083. }
  61084. if (light.needCube()) {
  61085. defines["SHADOWCUBE" + lightIndex] = true;
  61086. }
  61087. };
  61088. /**
  61089. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  61090. * defined in the generator but impacting the effect).
  61091. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  61092. * @param effect The effect we are binfing the information for
  61093. */
  61094. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  61095. var light = this._light;
  61096. var scene = this._scene;
  61097. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61098. return;
  61099. }
  61100. var camera = scene.activeCamera;
  61101. if (!camera) {
  61102. return;
  61103. }
  61104. var shadowMap = this.getShadowMap();
  61105. if (!shadowMap) {
  61106. return;
  61107. }
  61108. if (!light.needCube()) {
  61109. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61110. }
  61111. // Only PCF uses depth stencil texture.
  61112. if (this._filter === ShadowGenerator.FILTER_PCF) {
  61113. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61114. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61115. }
  61116. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  61117. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61118. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  61119. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61120. }
  61121. else {
  61122. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61123. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61124. }
  61125. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61126. };
  61127. /**
  61128. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61129. * (eq to shadow prjection matrix * light transform matrix)
  61130. * @returns The transform matrix used to create the shadow map
  61131. */
  61132. ShadowGenerator.prototype.getTransformMatrix = function () {
  61133. var scene = this._scene;
  61134. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61135. return this._transformMatrix;
  61136. }
  61137. this._currentRenderID = scene.getRenderId();
  61138. this._currentFaceIndexCache = this._currentFaceIndex;
  61139. var lightPosition = this._light.position;
  61140. if (this._light.computeTransformedInformation()) {
  61141. lightPosition = this._light.transformedPosition;
  61142. }
  61143. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61144. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61145. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61146. }
  61147. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61148. this._cachedPosition.copyFrom(lightPosition);
  61149. this._cachedDirection.copyFrom(this._lightDirection);
  61150. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61151. var shadowMap = this.getShadowMap();
  61152. if (shadowMap) {
  61153. var renderList = shadowMap.renderList;
  61154. if (renderList) {
  61155. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61156. }
  61157. }
  61158. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61159. }
  61160. return this._transformMatrix;
  61161. };
  61162. /**
  61163. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61164. * Cube and 2D textures for instance.
  61165. */
  61166. ShadowGenerator.prototype.recreateShadowMap = function () {
  61167. var shadowMap = this._shadowMap;
  61168. if (!shadowMap) {
  61169. return;
  61170. }
  61171. // Track render list.
  61172. var renderList = shadowMap.renderList;
  61173. // Clean up existing data.
  61174. this._disposeRTTandPostProcesses();
  61175. // Reinitializes.
  61176. this._initializeGenerator();
  61177. // Reaffect the filter to ensure a correct fallback if necessary.
  61178. this.filter = this.filter;
  61179. // Reaffect the filter.
  61180. this._applyFilterValues();
  61181. // Reaffect Render List.
  61182. this._shadowMap.renderList = renderList;
  61183. };
  61184. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61185. if (this._shadowMap2) {
  61186. this._shadowMap2.dispose();
  61187. this._shadowMap2 = null;
  61188. }
  61189. if (this._boxBlurPostprocess) {
  61190. this._boxBlurPostprocess.dispose();
  61191. this._boxBlurPostprocess = null;
  61192. }
  61193. if (this._kernelBlurXPostprocess) {
  61194. this._kernelBlurXPostprocess.dispose();
  61195. this._kernelBlurXPostprocess = null;
  61196. }
  61197. if (this._kernelBlurYPostprocess) {
  61198. this._kernelBlurYPostprocess.dispose();
  61199. this._kernelBlurYPostprocess = null;
  61200. }
  61201. this._blurPostProcesses = [];
  61202. };
  61203. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61204. if (this._shadowMap) {
  61205. this._shadowMap.dispose();
  61206. this._shadowMap = null;
  61207. }
  61208. this._disposeBlurPostProcesses();
  61209. };
  61210. /**
  61211. * Disposes the ShadowGenerator.
  61212. * Returns nothing.
  61213. */
  61214. ShadowGenerator.prototype.dispose = function () {
  61215. this._disposeRTTandPostProcesses();
  61216. if (this._light) {
  61217. this._light._shadowGenerator = null;
  61218. this._light._markMeshesAsLightDirty();
  61219. }
  61220. };
  61221. /**
  61222. * Serializes the shadow generator setup to a json object.
  61223. * @returns The serialized JSON object
  61224. */
  61225. ShadowGenerator.prototype.serialize = function () {
  61226. var serializationObject = {};
  61227. var shadowMap = this.getShadowMap();
  61228. if (!shadowMap) {
  61229. return serializationObject;
  61230. }
  61231. serializationObject.lightId = this._light.id;
  61232. serializationObject.mapSize = shadowMap.getRenderSize();
  61233. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  61234. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  61235. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61236. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61237. serializationObject.usePoissonSampling = this.usePoissonSampling;
  61238. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  61239. serializationObject.depthScale = this.depthScale;
  61240. serializationObject.darkness = this.getDarkness();
  61241. serializationObject.blurBoxOffset = this.blurBoxOffset;
  61242. serializationObject.blurKernel = this.blurKernel;
  61243. serializationObject.blurScale = this.blurScale;
  61244. serializationObject.useKernelBlur = this.useKernelBlur;
  61245. serializationObject.transparencyShadow = this._transparencyShadow;
  61246. serializationObject.bias = this.bias;
  61247. serializationObject.normalBias = this.normalBias;
  61248. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  61249. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  61250. serializationObject.filteringQuality = this.filteringQuality;
  61251. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  61252. serializationObject.renderList = [];
  61253. if (shadowMap.renderList) {
  61254. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  61255. var mesh = shadowMap.renderList[meshIndex];
  61256. serializationObject.renderList.push(mesh.id);
  61257. }
  61258. }
  61259. return serializationObject;
  61260. };
  61261. /**
  61262. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  61263. * @param parsedShadowGenerator The JSON object to parse
  61264. * @param scene The scene to create the shadow map for
  61265. * @returns The parsed shadow generator
  61266. */
  61267. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  61268. //casting to point light, as light is missing the position attr and typescript complains.
  61269. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  61270. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  61271. var shadowMap = shadowGenerator.getShadowMap();
  61272. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  61273. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  61274. meshes.forEach(function (mesh) {
  61275. if (!shadowMap) {
  61276. return;
  61277. }
  61278. if (!shadowMap.renderList) {
  61279. shadowMap.renderList = [];
  61280. }
  61281. shadowMap.renderList.push(mesh);
  61282. });
  61283. }
  61284. if (parsedShadowGenerator.usePoissonSampling) {
  61285. shadowGenerator.usePoissonSampling = true;
  61286. }
  61287. else if (parsedShadowGenerator.useExponentialShadowMap) {
  61288. shadowGenerator.useExponentialShadowMap = true;
  61289. }
  61290. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  61291. shadowGenerator.useBlurExponentialShadowMap = true;
  61292. }
  61293. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61294. shadowGenerator.useCloseExponentialShadowMap = true;
  61295. }
  61296. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61297. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61298. }
  61299. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  61300. shadowGenerator.usePercentageCloserFiltering = true;
  61301. }
  61302. else if (parsedShadowGenerator.useContactHardeningShadow) {
  61303. shadowGenerator.useContactHardeningShadow = true;
  61304. }
  61305. if (parsedShadowGenerator.filteringQuality) {
  61306. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  61307. }
  61308. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  61309. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  61310. }
  61311. else if (parsedShadowGenerator.useVarianceShadowMap) {
  61312. shadowGenerator.useExponentialShadowMap = true;
  61313. }
  61314. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  61315. shadowGenerator.useBlurExponentialShadowMap = true;
  61316. }
  61317. if (parsedShadowGenerator.depthScale) {
  61318. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  61319. }
  61320. if (parsedShadowGenerator.blurScale) {
  61321. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  61322. }
  61323. if (parsedShadowGenerator.blurBoxOffset) {
  61324. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  61325. }
  61326. if (parsedShadowGenerator.useKernelBlur) {
  61327. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  61328. }
  61329. if (parsedShadowGenerator.blurKernel) {
  61330. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  61331. }
  61332. if (parsedShadowGenerator.bias !== undefined) {
  61333. shadowGenerator.bias = parsedShadowGenerator.bias;
  61334. }
  61335. if (parsedShadowGenerator.normalBias !== undefined) {
  61336. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  61337. }
  61338. if (parsedShadowGenerator.darkness) {
  61339. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  61340. }
  61341. if (parsedShadowGenerator.transparencyShadow) {
  61342. shadowGenerator.setTransparencyShadow(true);
  61343. }
  61344. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  61345. return shadowGenerator;
  61346. };
  61347. /**
  61348. * Shadow generator mode None: no filtering applied.
  61349. */
  61350. ShadowGenerator.FILTER_NONE = 0;
  61351. /**
  61352. * Shadow generator mode ESM: Exponential Shadow Mapping.
  61353. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61354. */
  61355. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  61356. /**
  61357. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  61358. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  61359. */
  61360. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  61361. /**
  61362. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  61363. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61364. */
  61365. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  61366. /**
  61367. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  61368. * edge artifacts on steep falloff.
  61369. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61370. */
  61371. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  61372. /**
  61373. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  61374. * edge artifacts on steep falloff.
  61375. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  61376. */
  61377. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  61378. /**
  61379. * Shadow generator mode PCF: Percentage Closer Filtering
  61380. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  61381. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  61382. */
  61383. ShadowGenerator.FILTER_PCF = 6;
  61384. /**
  61385. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  61386. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  61387. * Contact Hardening
  61388. */
  61389. ShadowGenerator.FILTER_PCSS = 7;
  61390. /**
  61391. * Reserved for PCF and PCSS
  61392. * Highest Quality.
  61393. *
  61394. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  61395. *
  61396. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  61397. */
  61398. ShadowGenerator.QUALITY_HIGH = 0;
  61399. /**
  61400. * Reserved for PCF and PCSS
  61401. * Good tradeoff for quality/perf cross devices
  61402. *
  61403. * Execute PCF on a 3*3 kernel.
  61404. *
  61405. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  61406. */
  61407. ShadowGenerator.QUALITY_MEDIUM = 1;
  61408. /**
  61409. * Reserved for PCF and PCSS
  61410. * The lowest quality but the fastest.
  61411. *
  61412. * Execute PCF on a 1*1 kernel.
  61413. *
  61414. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  61415. */
  61416. ShadowGenerator.QUALITY_LOW = 2;
  61417. return ShadowGenerator;
  61418. }());
  61419. BABYLON.ShadowGenerator = ShadowGenerator;
  61420. })(BABYLON || (BABYLON = {}));
  61421. //# sourceMappingURL=babylon.shadowGenerator.js.map
  61422. "use strict";
  61423. var BABYLON;
  61424. (function (BABYLON) {
  61425. var DefaultLoadingScreen = /** @class */ (function () {
  61426. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  61427. if (_loadingText === void 0) { _loadingText = ""; }
  61428. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  61429. var _this = this;
  61430. this._renderingCanvas = _renderingCanvas;
  61431. this._loadingText = _loadingText;
  61432. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  61433. // Resize
  61434. this._resizeLoadingUI = function () {
  61435. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  61436. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  61437. if (!_this._loadingDiv) {
  61438. return;
  61439. }
  61440. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  61441. _this._loadingDiv.style.left = canvasRect.left + "px";
  61442. _this._loadingDiv.style.top = canvasRect.top + "px";
  61443. _this._loadingDiv.style.width = canvasRect.width + "px";
  61444. _this._loadingDiv.style.height = canvasRect.height + "px";
  61445. };
  61446. }
  61447. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  61448. if (this._loadingDiv) {
  61449. // Do not add a loading screen if there is already one
  61450. return;
  61451. }
  61452. this._loadingDiv = document.createElement("div");
  61453. this._loadingDiv.id = "babylonjsLoadingDiv";
  61454. this._loadingDiv.style.opacity = "0";
  61455. this._loadingDiv.style.transition = "opacity 1.5s ease";
  61456. this._loadingDiv.style.pointerEvents = "none";
  61457. // Loading text
  61458. this._loadingTextDiv = document.createElement("div");
  61459. this._loadingTextDiv.style.position = "absolute";
  61460. this._loadingTextDiv.style.left = "0";
  61461. this._loadingTextDiv.style.top = "50%";
  61462. this._loadingTextDiv.style.marginTop = "80px";
  61463. this._loadingTextDiv.style.width = "100%";
  61464. this._loadingTextDiv.style.height = "20px";
  61465. this._loadingTextDiv.style.fontFamily = "Arial";
  61466. this._loadingTextDiv.style.fontSize = "14px";
  61467. this._loadingTextDiv.style.color = "white";
  61468. this._loadingTextDiv.style.textAlign = "center";
  61469. this._loadingTextDiv.innerHTML = "Loading";
  61470. this._loadingDiv.appendChild(this._loadingTextDiv);
  61471. //set the predefined text
  61472. this._loadingTextDiv.innerHTML = this._loadingText;
  61473. // Generating keyframes
  61474. var style = document.createElement('style');
  61475. style.type = 'text/css';
  61476. 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 }";
  61477. style.innerHTML = keyFrames;
  61478. document.getElementsByTagName('head')[0].appendChild(style);
  61479. // Loading img
  61480. var imgBack = new Image();
  61481. 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";
  61482. imgBack.style.position = "absolute";
  61483. imgBack.style.left = "50%";
  61484. imgBack.style.top = "50%";
  61485. imgBack.style.marginLeft = "-60px";
  61486. imgBack.style.marginTop = "-60px";
  61487. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  61488. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  61489. imgBack.style.transformOrigin = "50% 50%";
  61490. imgBack.style.webkitTransformOrigin = "50% 50%";
  61491. this._loadingDiv.appendChild(imgBack);
  61492. this._resizeLoadingUI();
  61493. window.addEventListener("resize", this._resizeLoadingUI);
  61494. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61495. document.body.appendChild(this._loadingDiv);
  61496. this._loadingDiv.style.opacity = "1";
  61497. };
  61498. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  61499. var _this = this;
  61500. if (!this._loadingDiv) {
  61501. return;
  61502. }
  61503. var onTransitionEnd = function () {
  61504. if (!_this._loadingDiv) {
  61505. return;
  61506. }
  61507. document.body.removeChild(_this._loadingDiv);
  61508. window.removeEventListener("resize", _this._resizeLoadingUI);
  61509. _this._loadingDiv = null;
  61510. };
  61511. this._loadingDiv.style.opacity = "0";
  61512. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  61513. };
  61514. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  61515. set: function (text) {
  61516. this._loadingText = text;
  61517. if (this._loadingTextDiv) {
  61518. this._loadingTextDiv.innerHTML = this._loadingText;
  61519. }
  61520. },
  61521. enumerable: true,
  61522. configurable: true
  61523. });
  61524. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  61525. get: function () {
  61526. return this._loadingDivBackgroundColor;
  61527. },
  61528. set: function (color) {
  61529. this._loadingDivBackgroundColor = color;
  61530. if (!this._loadingDiv) {
  61531. return;
  61532. }
  61533. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  61534. },
  61535. enumerable: true,
  61536. configurable: true
  61537. });
  61538. return DefaultLoadingScreen;
  61539. }());
  61540. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  61541. })(BABYLON || (BABYLON = {}));
  61542. //# sourceMappingURL=babylon.loadingScreen.js.map
  61543. "use strict";
  61544. var BABYLON;
  61545. (function (BABYLON) {
  61546. var SceneLoaderProgressEvent = /** @class */ (function () {
  61547. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  61548. this.lengthComputable = lengthComputable;
  61549. this.loaded = loaded;
  61550. this.total = total;
  61551. }
  61552. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  61553. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  61554. };
  61555. return SceneLoaderProgressEvent;
  61556. }());
  61557. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  61558. var SceneLoader = /** @class */ (function () {
  61559. function SceneLoader() {
  61560. }
  61561. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  61562. get: function () {
  61563. return 0;
  61564. },
  61565. enumerable: true,
  61566. configurable: true
  61567. });
  61568. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  61569. get: function () {
  61570. return 1;
  61571. },
  61572. enumerable: true,
  61573. configurable: true
  61574. });
  61575. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  61576. get: function () {
  61577. return 2;
  61578. },
  61579. enumerable: true,
  61580. configurable: true
  61581. });
  61582. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  61583. get: function () {
  61584. return 3;
  61585. },
  61586. enumerable: true,
  61587. configurable: true
  61588. });
  61589. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  61590. get: function () {
  61591. return SceneLoader._ForceFullSceneLoadingForIncremental;
  61592. },
  61593. set: function (value) {
  61594. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  61595. },
  61596. enumerable: true,
  61597. configurable: true
  61598. });
  61599. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  61600. get: function () {
  61601. return SceneLoader._ShowLoadingScreen;
  61602. },
  61603. set: function (value) {
  61604. SceneLoader._ShowLoadingScreen = value;
  61605. },
  61606. enumerable: true,
  61607. configurable: true
  61608. });
  61609. Object.defineProperty(SceneLoader, "loggingLevel", {
  61610. get: function () {
  61611. return SceneLoader._loggingLevel;
  61612. },
  61613. set: function (value) {
  61614. SceneLoader._loggingLevel = value;
  61615. },
  61616. enumerable: true,
  61617. configurable: true
  61618. });
  61619. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  61620. get: function () {
  61621. return SceneLoader._CleanBoneMatrixWeights;
  61622. },
  61623. set: function (value) {
  61624. SceneLoader._CleanBoneMatrixWeights = value;
  61625. },
  61626. enumerable: true,
  61627. configurable: true
  61628. });
  61629. SceneLoader._getDefaultPlugin = function () {
  61630. return SceneLoader._registeredPlugins[".babylon"];
  61631. };
  61632. SceneLoader._getPluginForExtension = function (extension) {
  61633. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  61634. if (registeredPlugin) {
  61635. return registeredPlugin;
  61636. }
  61637. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  61638. return SceneLoader._getDefaultPlugin();
  61639. };
  61640. SceneLoader._getPluginForDirectLoad = function (data) {
  61641. for (var extension in SceneLoader._registeredPlugins) {
  61642. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  61643. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  61644. return SceneLoader._registeredPlugins[extension];
  61645. }
  61646. }
  61647. return SceneLoader._getDefaultPlugin();
  61648. };
  61649. SceneLoader._getPluginForFilename = function (sceneFilename) {
  61650. if (sceneFilename.name) {
  61651. sceneFilename = sceneFilename.name;
  61652. }
  61653. var queryStringPosition = sceneFilename.indexOf("?");
  61654. if (queryStringPosition !== -1) {
  61655. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  61656. }
  61657. var dotPosition = sceneFilename.lastIndexOf(".");
  61658. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  61659. return SceneLoader._getPluginForExtension(extension);
  61660. };
  61661. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  61662. SceneLoader._getDirectLoad = function (sceneFilename) {
  61663. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  61664. return sceneFilename.substr(5);
  61665. }
  61666. return null;
  61667. };
  61668. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  61669. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  61670. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  61671. var plugin;
  61672. if (registeredPlugin.plugin.createPlugin) {
  61673. plugin = registeredPlugin.plugin.createPlugin();
  61674. }
  61675. else {
  61676. plugin = registeredPlugin.plugin;
  61677. }
  61678. var useArrayBuffer = registeredPlugin.isBinary;
  61679. var database;
  61680. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  61681. var dataCallback = function (data, responseURL) {
  61682. if (scene.isDisposed) {
  61683. onError("Scene has been disposed");
  61684. return;
  61685. }
  61686. scene.database = database;
  61687. onSuccess(plugin, data, responseURL);
  61688. };
  61689. var request = null;
  61690. var pluginDisposed = false;
  61691. var onDisposeObservable = plugin.onDisposeObservable;
  61692. if (onDisposeObservable) {
  61693. onDisposeObservable.add(function () {
  61694. pluginDisposed = true;
  61695. if (request) {
  61696. request.abort();
  61697. request = null;
  61698. }
  61699. onDispose();
  61700. });
  61701. }
  61702. var manifestChecked = function () {
  61703. if (pluginDisposed) {
  61704. return;
  61705. }
  61706. var url = rootUrl + sceneFilename;
  61707. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  61708. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  61709. } : undefined, database, useArrayBuffer, function (request, exception) {
  61710. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  61711. });
  61712. };
  61713. if (directLoad) {
  61714. dataCallback(directLoad);
  61715. return plugin;
  61716. }
  61717. if (rootUrl.indexOf("file:") === -1) {
  61718. if (scene.getEngine().enableOfflineSupport) {
  61719. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  61720. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  61721. }
  61722. else {
  61723. manifestChecked();
  61724. }
  61725. }
  61726. else {
  61727. var fileOrString = sceneFilename;
  61728. if (fileOrString.name) {
  61729. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  61730. }
  61731. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  61732. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  61733. }
  61734. else {
  61735. onError("Unable to find file named " + sceneFilename);
  61736. }
  61737. }
  61738. return plugin;
  61739. };
  61740. // Public functions
  61741. SceneLoader.GetPluginForExtension = function (extension) {
  61742. return SceneLoader._getPluginForExtension(extension).plugin;
  61743. };
  61744. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  61745. return !!SceneLoader._registeredPlugins[extension];
  61746. };
  61747. SceneLoader.RegisterPlugin = function (plugin) {
  61748. if (typeof plugin.extensions === "string") {
  61749. var extension = plugin.extensions;
  61750. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61751. plugin: plugin,
  61752. isBinary: false
  61753. };
  61754. }
  61755. else {
  61756. var extensions = plugin.extensions;
  61757. Object.keys(extensions).forEach(function (extension) {
  61758. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  61759. plugin: plugin,
  61760. isBinary: extensions[extension].isBinary
  61761. };
  61762. });
  61763. }
  61764. };
  61765. /**
  61766. * Import meshes into a scene
  61767. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61768. * @param rootUrl a string that defines the root url for scene and resources
  61769. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61770. * @param scene the instance of BABYLON.Scene to append to
  61771. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  61772. * @param onProgress a callback with a progress event for each file being loaded
  61773. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61774. * @param pluginExtension the extension used to determine the plugin
  61775. * @returns The loaded plugin
  61776. */
  61777. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61778. if (onSuccess === void 0) { onSuccess = null; }
  61779. if (onProgress === void 0) { onProgress = null; }
  61780. if (onError === void 0) { onError = null; }
  61781. if (pluginExtension === void 0) { pluginExtension = null; }
  61782. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61783. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61784. return null;
  61785. }
  61786. var loadingToken = {};
  61787. scene._addPendingData(loadingToken);
  61788. var disposeHandler = function () {
  61789. scene._removePendingData(loadingToken);
  61790. };
  61791. var errorHandler = function (message, exception) {
  61792. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  61793. if (onError) {
  61794. onError(scene, errorMessage, exception);
  61795. }
  61796. else {
  61797. BABYLON.Tools.Error(errorMessage);
  61798. // should the exception be thrown?
  61799. }
  61800. disposeHandler();
  61801. };
  61802. var progressHandler = onProgress ? function (event) {
  61803. try {
  61804. onProgress(event);
  61805. }
  61806. catch (e) {
  61807. errorHandler("Error in onProgress callback", e);
  61808. }
  61809. } : undefined;
  61810. var successHandler = function (meshes, particleSystems, skeletons) {
  61811. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  61812. if (onSuccess) {
  61813. try {
  61814. onSuccess(meshes, particleSystems, skeletons);
  61815. }
  61816. catch (e) {
  61817. errorHandler("Error in onSuccess callback", e);
  61818. }
  61819. }
  61820. scene._removePendingData(loadingToken);
  61821. };
  61822. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61823. if (plugin.rewriteRootURL) {
  61824. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  61825. }
  61826. if (sceneFilename === "") {
  61827. if (sceneFilename === "") {
  61828. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61829. }
  61830. }
  61831. if (plugin.importMesh) {
  61832. var syncedPlugin = plugin;
  61833. var meshes = new Array();
  61834. var particleSystems = new Array();
  61835. var skeletons = new Array();
  61836. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  61837. return;
  61838. }
  61839. scene.loadingPluginName = plugin.name;
  61840. successHandler(meshes, particleSystems, skeletons);
  61841. }
  61842. else {
  61843. var asyncedPlugin = plugin;
  61844. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  61845. scene.loadingPluginName = plugin.name;
  61846. successHandler(result.meshes, result.particleSystems, result.skeletons);
  61847. }).catch(function (error) {
  61848. errorHandler(error.message, error);
  61849. });
  61850. }
  61851. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  61852. };
  61853. /**
  61854. * Import meshes into a scene
  61855. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  61856. * @param rootUrl a string that defines the root url for scene and resources
  61857. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61858. * @param scene the instance of BABYLON.Scene to append to
  61859. * @param onProgress a callback with a progress event for each file being loaded
  61860. * @param pluginExtension the extension used to determine the plugin
  61861. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  61862. */
  61863. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61864. if (onProgress === void 0) { onProgress = null; }
  61865. if (pluginExtension === void 0) { pluginExtension = null; }
  61866. return new Promise(function (resolve, reject) {
  61867. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61868. resolve({
  61869. meshes: meshes,
  61870. particleSystems: particleSystems,
  61871. skeletons: skeletons
  61872. });
  61873. }, onProgress, function (scene, message, exception) {
  61874. reject(exception || new Error(message));
  61875. });
  61876. });
  61877. };
  61878. /**
  61879. * Load a scene
  61880. * @param rootUrl a string that defines the root url for scene and resources
  61881. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61882. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61883. * @param onSuccess a callback with the scene when import succeeds
  61884. * @param onProgress a callback with a progress event for each file being loaded
  61885. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61886. * @param pluginExtension the extension used to determine the plugin
  61887. * @returns The loaded plugin
  61888. */
  61889. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  61890. if (onSuccess === void 0) { onSuccess = null; }
  61891. if (onProgress === void 0) { onProgress = null; }
  61892. if (onError === void 0) { onError = null; }
  61893. if (pluginExtension === void 0) { pluginExtension = null; }
  61894. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  61895. };
  61896. /**
  61897. * Load a scene
  61898. * @param rootUrl a string that defines the root url for scene and resources
  61899. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61900. * @param engine is the instance of BABYLON.Engine to use to create the scene
  61901. * @param onProgress a callback with a progress event for each file being loaded
  61902. * @param pluginExtension the extension used to determine the plugin
  61903. * @returns The loaded scene
  61904. */
  61905. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  61906. if (onProgress === void 0) { onProgress = null; }
  61907. if (pluginExtension === void 0) { pluginExtension = null; }
  61908. return new Promise(function (resolve, reject) {
  61909. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  61910. resolve(scene);
  61911. }, onProgress, function (scene, message, exception) {
  61912. reject(exception || new Error(message));
  61913. }, pluginExtension);
  61914. });
  61915. };
  61916. /**
  61917. * Append a scene
  61918. * @param rootUrl a string that defines the root url for scene and resources
  61919. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  61920. * @param scene is the instance of BABYLON.Scene to append to
  61921. * @param onSuccess a callback with the scene when import succeeds
  61922. * @param onProgress a callback with a progress event for each file being loaded
  61923. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  61924. * @param pluginExtension the extension used to determine the plugin
  61925. * @returns The loaded plugin
  61926. */
  61927. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  61928. if (onSuccess === void 0) { onSuccess = null; }
  61929. if (onProgress === void 0) { onProgress = null; }
  61930. if (onError === void 0) { onError = null; }
  61931. if (pluginExtension === void 0) { pluginExtension = null; }
  61932. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  61933. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  61934. return null;
  61935. }
  61936. if (SceneLoader.ShowLoadingScreen) {
  61937. scene.getEngine().displayLoadingUI();
  61938. }
  61939. var loadingToken = {};
  61940. scene._addPendingData(loadingToken);
  61941. var disposeHandler = function () {
  61942. scene._removePendingData(loadingToken);
  61943. scene.getEngine().hideLoadingUI();
  61944. };
  61945. var errorHandler = function (message, exception) {
  61946. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  61947. if (onError) {
  61948. onError(scene, errorMessage, exception);
  61949. }
  61950. else {
  61951. BABYLON.Tools.Error(errorMessage);
  61952. // should the exception be thrown?
  61953. }
  61954. disposeHandler();
  61955. };
  61956. var progressHandler = onProgress ? function (event) {
  61957. try {
  61958. onProgress(event);
  61959. }
  61960. catch (e) {
  61961. errorHandler("Error in onProgress callback", e);
  61962. }
  61963. } : undefined;
  61964. var successHandler = function () {
  61965. if (onSuccess) {
  61966. try {
  61967. onSuccess(scene);
  61968. }
  61969. catch (e) {
  61970. errorHandler("Error in onSuccess callback", e);
  61971. }
  61972. }
  61973. scene._removePendingData(loadingToken);
  61974. };
  61975. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  61976. if (sceneFilename === "") {
  61977. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  61978. }
  61979. if (plugin.load) {
  61980. var syncedPlugin = plugin;
  61981. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  61982. return;
  61983. }
  61984. scene.loadingPluginName = plugin.name;
  61985. successHandler();
  61986. }
  61987. else {
  61988. var asyncedPlugin = plugin;
  61989. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  61990. scene.loadingPluginName = plugin.name;
  61991. successHandler();
  61992. }).catch(function (error) {
  61993. errorHandler(error.message, error);
  61994. });
  61995. }
  61996. if (SceneLoader.ShowLoadingScreen) {
  61997. scene.executeWhenReady(function () {
  61998. scene.getEngine().hideLoadingUI();
  61999. });
  62000. }
  62001. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62002. };
  62003. /**
  62004. * Append a scene
  62005. * @param rootUrl a string that defines the root url for scene and resources
  62006. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62007. * @param scene is the instance of BABYLON.Scene to append to
  62008. * @param onProgress a callback with a progress event for each file being loaded
  62009. * @param pluginExtension the extension used to determine the plugin
  62010. * @returns The given scene
  62011. */
  62012. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62013. if (onProgress === void 0) { onProgress = null; }
  62014. if (pluginExtension === void 0) { pluginExtension = null; }
  62015. return new Promise(function (resolve, reject) {
  62016. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  62017. resolve(scene);
  62018. }, onProgress, function (scene, message, exception) {
  62019. reject(exception || new Error(message));
  62020. }, pluginExtension);
  62021. });
  62022. };
  62023. /**
  62024. * Load a scene into an asset container
  62025. * @param rootUrl a string that defines the root url for scene and resources
  62026. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62027. * @param scene is the instance of BABYLON.Scene to append to
  62028. * @param onSuccess a callback with the scene when import succeeds
  62029. * @param onProgress a callback with a progress event for each file being loaded
  62030. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62031. * @param pluginExtension the extension used to determine the plugin
  62032. * @returns The loaded plugin
  62033. */
  62034. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62035. if (onSuccess === void 0) { onSuccess = null; }
  62036. if (onProgress === void 0) { onProgress = null; }
  62037. if (onError === void 0) { onError = null; }
  62038. if (pluginExtension === void 0) { pluginExtension = null; }
  62039. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62040. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62041. return null;
  62042. }
  62043. var loadingToken = {};
  62044. scene._addPendingData(loadingToken);
  62045. var disposeHandler = function () {
  62046. scene._removePendingData(loadingToken);
  62047. };
  62048. var errorHandler = function (message, exception) {
  62049. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62050. if (onError) {
  62051. onError(scene, errorMessage, exception);
  62052. }
  62053. else {
  62054. BABYLON.Tools.Error(errorMessage);
  62055. // should the exception be thrown?
  62056. }
  62057. disposeHandler();
  62058. };
  62059. var progressHandler = onProgress ? function (event) {
  62060. try {
  62061. onProgress(event);
  62062. }
  62063. catch (e) {
  62064. errorHandler("Error in onProgress callback", e);
  62065. }
  62066. } : undefined;
  62067. var successHandler = function (assets) {
  62068. if (onSuccess) {
  62069. try {
  62070. onSuccess(assets);
  62071. }
  62072. catch (e) {
  62073. errorHandler("Error in onSuccess callback", e);
  62074. }
  62075. }
  62076. scene._removePendingData(loadingToken);
  62077. };
  62078. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62079. if (plugin.loadAssetContainer) {
  62080. var syncedPlugin = plugin;
  62081. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  62082. if (!assetContainer) {
  62083. return;
  62084. }
  62085. scene.loadingPluginName = plugin.name;
  62086. successHandler(assetContainer);
  62087. }
  62088. else if (plugin.loadAssetContainerAsync) {
  62089. var asyncedPlugin = plugin;
  62090. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  62091. scene.loadingPluginName = plugin.name;
  62092. successHandler(assetContainer);
  62093. }).catch(function (error) {
  62094. errorHandler(error.message, error);
  62095. });
  62096. }
  62097. else {
  62098. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  62099. }
  62100. if (SceneLoader.ShowLoadingScreen) {
  62101. scene.executeWhenReady(function () {
  62102. scene.getEngine().hideLoadingUI();
  62103. });
  62104. }
  62105. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62106. };
  62107. /**
  62108. * Load a scene into an asset container
  62109. * @param rootUrl a string that defines the root url for scene and resources
  62110. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62111. * @param scene is the instance of BABYLON.Scene to append to
  62112. * @param onProgress a callback with a progress event for each file being loaded
  62113. * @param pluginExtension the extension used to determine the plugin
  62114. * @returns The loaded asset container
  62115. */
  62116. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62117. if (onProgress === void 0) { onProgress = null; }
  62118. if (pluginExtension === void 0) { pluginExtension = null; }
  62119. return new Promise(function (resolve, reject) {
  62120. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  62121. resolve(assetContainer);
  62122. }, onProgress, function (scene, message, exception) {
  62123. reject(exception || new Error(message));
  62124. }, pluginExtension);
  62125. });
  62126. };
  62127. // Flags
  62128. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  62129. SceneLoader._ShowLoadingScreen = true;
  62130. SceneLoader._CleanBoneMatrixWeights = false;
  62131. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  62132. // Members
  62133. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  62134. SceneLoader._registeredPlugins = {};
  62135. return SceneLoader;
  62136. }());
  62137. BABYLON.SceneLoader = SceneLoader;
  62138. ;
  62139. })(BABYLON || (BABYLON = {}));
  62140. //# sourceMappingURL=babylon.sceneLoader.js.map
  62141. "use strict";
  62142. var BABYLON;
  62143. (function (BABYLON) {
  62144. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  62145. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62146. var parsedMaterial = parsedData.materials[index];
  62147. if (parsedMaterial.id === id) {
  62148. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62149. }
  62150. }
  62151. return null;
  62152. };
  62153. var isDescendantOf = function (mesh, names, hierarchyIds) {
  62154. for (var i in names) {
  62155. if (mesh.name === names[i]) {
  62156. hierarchyIds.push(mesh.id);
  62157. return true;
  62158. }
  62159. }
  62160. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62161. hierarchyIds.push(mesh.id);
  62162. return true;
  62163. }
  62164. return false;
  62165. };
  62166. var logOperation = function (operation, producer) {
  62167. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  62168. };
  62169. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  62170. if (addToScene === void 0) { addToScene = false; }
  62171. var container = new BABYLON.AssetContainer(scene);
  62172. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62173. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62174. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62175. // and avoid problems with multiple concurrent .babylon loads.
  62176. var log = "importScene has failed JSON parse";
  62177. try {
  62178. var parsedData = JSON.parse(data);
  62179. log = "";
  62180. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62181. var index;
  62182. var cache;
  62183. // Lights
  62184. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  62185. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  62186. var parsedLight = parsedData.lights[index];
  62187. var light = BABYLON.Light.Parse(parsedLight, scene);
  62188. if (light) {
  62189. container.lights.push(light);
  62190. log += (index === 0 ? "\n\tLights:" : "");
  62191. log += "\n\t\t" + light.toString(fullDetails);
  62192. }
  62193. }
  62194. }
  62195. // Animations
  62196. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  62197. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  62198. var parsedAnimation = parsedData.animations[index];
  62199. var animation = BABYLON.Animation.Parse(parsedAnimation);
  62200. scene.animations.push(animation);
  62201. container.animations.push(animation);
  62202. log += (index === 0 ? "\n\tAnimations:" : "");
  62203. log += "\n\t\t" + animation.toString(fullDetails);
  62204. }
  62205. }
  62206. // Materials
  62207. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62208. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62209. var parsedMaterial = parsedData.materials[index];
  62210. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62211. container.materials.push(mat);
  62212. log += (index === 0 ? "\n\tMaterials:" : "");
  62213. log += "\n\t\t" + mat.toString(fullDetails);
  62214. }
  62215. }
  62216. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62217. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62218. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62219. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62220. container.multiMaterials.push(mmat);
  62221. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  62222. log += "\n\t\t" + mmat.toString(fullDetails);
  62223. }
  62224. }
  62225. // Morph targets
  62226. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  62227. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  62228. var managerData = _a[_i];
  62229. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  62230. }
  62231. }
  62232. // Skeletons
  62233. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62234. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  62235. var parsedSkeleton = parsedData.skeletons[index];
  62236. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62237. container.skeletons.push(skeleton);
  62238. log += (index === 0 ? "\n\tSkeletons:" : "");
  62239. log += "\n\t\t" + skeleton.toString(fullDetails);
  62240. }
  62241. }
  62242. // Geometries
  62243. var geometries = parsedData.geometries;
  62244. if (geometries !== undefined && geometries !== null) {
  62245. var addedGeometry = new Array();
  62246. // Boxes
  62247. var boxes = geometries.boxes;
  62248. if (boxes !== undefined && boxes !== null) {
  62249. for (index = 0, cache = boxes.length; index < cache; index++) {
  62250. var parsedBox = boxes[index];
  62251. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  62252. }
  62253. }
  62254. // Spheres
  62255. var spheres = geometries.spheres;
  62256. if (spheres !== undefined && spheres !== null) {
  62257. for (index = 0, cache = spheres.length; index < cache; index++) {
  62258. var parsedSphere = spheres[index];
  62259. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  62260. }
  62261. }
  62262. // Cylinders
  62263. var cylinders = geometries.cylinders;
  62264. if (cylinders !== undefined && cylinders !== null) {
  62265. for (index = 0, cache = cylinders.length; index < cache; index++) {
  62266. var parsedCylinder = cylinders[index];
  62267. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  62268. }
  62269. }
  62270. // Toruses
  62271. var toruses = geometries.toruses;
  62272. if (toruses !== undefined && toruses !== null) {
  62273. for (index = 0, cache = toruses.length; index < cache; index++) {
  62274. var parsedTorus = toruses[index];
  62275. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  62276. }
  62277. }
  62278. // Grounds
  62279. var grounds = geometries.grounds;
  62280. if (grounds !== undefined && grounds !== null) {
  62281. for (index = 0, cache = grounds.length; index < cache; index++) {
  62282. var parsedGround = grounds[index];
  62283. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  62284. }
  62285. }
  62286. // Planes
  62287. var planes = geometries.planes;
  62288. if (planes !== undefined && planes !== null) {
  62289. for (index = 0, cache = planes.length; index < cache; index++) {
  62290. var parsedPlane = planes[index];
  62291. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  62292. }
  62293. }
  62294. // TorusKnots
  62295. var torusKnots = geometries.torusKnots;
  62296. if (torusKnots !== undefined && torusKnots !== null) {
  62297. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  62298. var parsedTorusKnot = torusKnots[index];
  62299. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  62300. }
  62301. }
  62302. // VertexData
  62303. var vertexData = geometries.vertexData;
  62304. if (vertexData !== undefined && vertexData !== null) {
  62305. for (index = 0, cache = vertexData.length; index < cache; index++) {
  62306. var parsedVertexData = vertexData[index];
  62307. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  62308. }
  62309. }
  62310. addedGeometry.forEach(function (g) {
  62311. if (g) {
  62312. container.geometries.push(g);
  62313. }
  62314. });
  62315. }
  62316. // Transform nodes
  62317. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  62318. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  62319. var parsedTransformNode = parsedData.transformNodes[index];
  62320. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  62321. container.transformNodes.push(node);
  62322. }
  62323. }
  62324. // Meshes
  62325. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62326. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62327. var parsedMesh = parsedData.meshes[index];
  62328. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62329. container.meshes.push(mesh);
  62330. log += (index === 0 ? "\n\tMeshes:" : "");
  62331. log += "\n\t\t" + mesh.toString(fullDetails);
  62332. }
  62333. }
  62334. // Cameras
  62335. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  62336. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  62337. var parsedCamera = parsedData.cameras[index];
  62338. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  62339. container.cameras.push(camera);
  62340. log += (index === 0 ? "\n\tCameras:" : "");
  62341. log += "\n\t\t" + camera.toString(fullDetails);
  62342. }
  62343. }
  62344. // Browsing all the graph to connect the dots
  62345. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  62346. var camera = scene.cameras[index];
  62347. if (camera._waitingParentId) {
  62348. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  62349. camera._waitingParentId = null;
  62350. }
  62351. }
  62352. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62353. var light_1 = scene.lights[index];
  62354. if (light_1 && light_1._waitingParentId) {
  62355. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  62356. light_1._waitingParentId = null;
  62357. }
  62358. }
  62359. // Sounds
  62360. // TODO: add sound
  62361. var loadedSounds = [];
  62362. var loadedSound;
  62363. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  62364. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  62365. var parsedSound = parsedData.sounds[index];
  62366. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62367. if (!parsedSound.url)
  62368. parsedSound.url = parsedSound.name;
  62369. if (!loadedSounds[parsedSound.url]) {
  62370. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  62371. loadedSounds[parsedSound.url] = loadedSound;
  62372. container.sounds.push(loadedSound);
  62373. }
  62374. else {
  62375. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  62376. }
  62377. }
  62378. else {
  62379. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  62380. }
  62381. }
  62382. }
  62383. loadedSounds = [];
  62384. // Connect parents & children and parse actions
  62385. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  62386. var transformNode = scene.transformNodes[index];
  62387. if (transformNode._waitingParentId) {
  62388. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  62389. transformNode._waitingParentId = null;
  62390. }
  62391. }
  62392. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62393. var mesh = scene.meshes[index];
  62394. if (mesh._waitingParentId) {
  62395. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  62396. mesh._waitingParentId = null;
  62397. }
  62398. if (mesh._waitingActions) {
  62399. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  62400. mesh._waitingActions = null;
  62401. }
  62402. }
  62403. // freeze world matrix application
  62404. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62405. var currentMesh = scene.meshes[index];
  62406. if (currentMesh._waitingFreezeWorldMatrix) {
  62407. currentMesh.freezeWorldMatrix();
  62408. currentMesh._waitingFreezeWorldMatrix = null;
  62409. }
  62410. else {
  62411. currentMesh.computeWorldMatrix(true);
  62412. }
  62413. }
  62414. // Particles Systems
  62415. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62416. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62417. var parsedParticleSystem = parsedData.particleSystems[index];
  62418. if (parsedParticleSystem.activeParticleCount) {
  62419. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62420. container.particleSystems.push(ps);
  62421. }
  62422. else {
  62423. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62424. container.particleSystems.push(ps);
  62425. }
  62426. }
  62427. }
  62428. // Lens flares
  62429. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  62430. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  62431. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  62432. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  62433. container.lensFlareSystems.push(lf);
  62434. }
  62435. }
  62436. // Shadows
  62437. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  62438. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  62439. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  62440. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  62441. container.shadowGenerators.push(sg);
  62442. }
  62443. }
  62444. // Lights exclusions / inclusions
  62445. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  62446. var light_2 = scene.lights[index];
  62447. // Excluded check
  62448. if (light_2._excludedMeshesIds.length > 0) {
  62449. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  62450. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  62451. if (excludedMesh) {
  62452. light_2.excludedMeshes.push(excludedMesh);
  62453. }
  62454. }
  62455. light_2._excludedMeshesIds = [];
  62456. }
  62457. // Included check
  62458. if (light_2._includedOnlyMeshesIds.length > 0) {
  62459. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  62460. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  62461. if (includedOnlyMesh) {
  62462. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  62463. }
  62464. }
  62465. light_2._includedOnlyMeshesIds = [];
  62466. }
  62467. }
  62468. // Actions (scene)
  62469. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  62470. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  62471. }
  62472. if (!addToScene) {
  62473. container.removeAllFromScene();
  62474. }
  62475. }
  62476. catch (err) {
  62477. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  62478. if (onError) {
  62479. onError(msg, err);
  62480. }
  62481. else {
  62482. BABYLON.Tools.Log(msg);
  62483. throw err;
  62484. }
  62485. }
  62486. finally {
  62487. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62488. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62489. }
  62490. }
  62491. return container;
  62492. };
  62493. BABYLON.SceneLoader.RegisterPlugin({
  62494. name: "babylon.js",
  62495. extensions: ".babylon",
  62496. canDirectLoad: function (data) {
  62497. if (data.indexOf("babylon") !== -1) {
  62498. return true;
  62499. }
  62500. return false;
  62501. },
  62502. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  62503. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62504. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62505. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62506. // and avoid problems with multiple concurrent .babylon loads.
  62507. var log = "importMesh has failed JSON parse";
  62508. try {
  62509. var parsedData = JSON.parse(data);
  62510. log = "";
  62511. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62512. if (!meshesNames) {
  62513. meshesNames = null;
  62514. }
  62515. else if (!Array.isArray(meshesNames)) {
  62516. meshesNames = [meshesNames];
  62517. }
  62518. var hierarchyIds = new Array();
  62519. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  62520. var loadedSkeletonsIds = [];
  62521. var loadedMaterialsIds = [];
  62522. var index;
  62523. var cache;
  62524. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  62525. var parsedMesh = parsedData.meshes[index];
  62526. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  62527. if (meshesNames !== null) {
  62528. // Remove found mesh name from list.
  62529. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  62530. }
  62531. //Geometry?
  62532. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  62533. //does the file contain geometries?
  62534. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  62535. //find the correct geometry and add it to the scene
  62536. var found = false;
  62537. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  62538. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  62539. return;
  62540. }
  62541. else {
  62542. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  62543. if (parsedGeometryData.id === parsedMesh.geometryId) {
  62544. switch (geometryType) {
  62545. case "boxes":
  62546. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  62547. break;
  62548. case "spheres":
  62549. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  62550. break;
  62551. case "cylinders":
  62552. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  62553. break;
  62554. case "toruses":
  62555. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  62556. break;
  62557. case "grounds":
  62558. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  62559. break;
  62560. case "planes":
  62561. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  62562. break;
  62563. case "torusKnots":
  62564. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  62565. break;
  62566. case "vertexData":
  62567. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  62568. break;
  62569. }
  62570. found = true;
  62571. }
  62572. });
  62573. }
  62574. });
  62575. if (found === false) {
  62576. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  62577. }
  62578. }
  62579. }
  62580. // Material ?
  62581. if (parsedMesh.materialId) {
  62582. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  62583. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62584. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  62585. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  62586. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  62587. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  62588. var subMatId = parsedMultiMaterial.materials[matIndex];
  62589. loadedMaterialsIds.push(subMatId);
  62590. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  62591. if (mat) {
  62592. log += "\n\tMaterial " + mat.toString(fullDetails);
  62593. }
  62594. }
  62595. loadedMaterialsIds.push(parsedMultiMaterial.id);
  62596. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62597. if (mmat) {
  62598. materialFound = true;
  62599. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  62600. }
  62601. break;
  62602. }
  62603. }
  62604. }
  62605. if (materialFound === false) {
  62606. loadedMaterialsIds.push(parsedMesh.materialId);
  62607. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  62608. if (!mat) {
  62609. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  62610. }
  62611. else {
  62612. log += "\n\tMaterial " + mat.toString(fullDetails);
  62613. }
  62614. }
  62615. }
  62616. // Skeleton ?
  62617. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62618. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  62619. if (skeletonAlreadyLoaded === false) {
  62620. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  62621. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  62622. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  62623. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62624. skeletons.push(skeleton);
  62625. loadedSkeletonsIds.push(parsedSkeleton.id);
  62626. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  62627. }
  62628. }
  62629. }
  62630. }
  62631. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  62632. meshes.push(mesh);
  62633. log += "\n\tMesh " + mesh.toString(fullDetails);
  62634. }
  62635. }
  62636. // Connecting parents
  62637. var currentMesh;
  62638. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62639. currentMesh = scene.meshes[index];
  62640. if (currentMesh._waitingParentId) {
  62641. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  62642. currentMesh._waitingParentId = null;
  62643. }
  62644. }
  62645. // freeze and compute world matrix application
  62646. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  62647. currentMesh = scene.meshes[index];
  62648. if (currentMesh._waitingFreezeWorldMatrix) {
  62649. currentMesh.freezeWorldMatrix();
  62650. currentMesh._waitingFreezeWorldMatrix = null;
  62651. }
  62652. else {
  62653. currentMesh.computeWorldMatrix(true);
  62654. }
  62655. }
  62656. }
  62657. // Particles
  62658. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62659. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62660. var parsedParticleSystem = parsedData.particleSystems[index];
  62661. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  62662. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  62663. }
  62664. }
  62665. }
  62666. return true;
  62667. }
  62668. catch (err) {
  62669. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  62670. if (onError) {
  62671. onError(msg, err);
  62672. }
  62673. else {
  62674. BABYLON.Tools.Log(msg);
  62675. throw err;
  62676. }
  62677. }
  62678. finally {
  62679. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62680. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62681. }
  62682. }
  62683. return false;
  62684. },
  62685. load: function (scene, data, rootUrl, onError) {
  62686. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62687. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62688. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62689. // and avoid problems with multiple concurrent .babylon loads.
  62690. var log = "importScene has failed JSON parse";
  62691. try {
  62692. var parsedData = JSON.parse(data);
  62693. log = "";
  62694. // Scene
  62695. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  62696. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  62697. }
  62698. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  62699. scene.autoClear = parsedData.autoClear;
  62700. }
  62701. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  62702. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  62703. }
  62704. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  62705. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  62706. }
  62707. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  62708. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  62709. }
  62710. // Fog
  62711. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  62712. scene.fogMode = parsedData.fogMode;
  62713. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  62714. scene.fogStart = parsedData.fogStart;
  62715. scene.fogEnd = parsedData.fogEnd;
  62716. scene.fogDensity = parsedData.fogDensity;
  62717. log += "\tFog mode for scene: ";
  62718. switch (scene.fogMode) {
  62719. // getters not compiling, so using hardcoded
  62720. case 1:
  62721. log += "exp\n";
  62722. break;
  62723. case 2:
  62724. log += "exp2\n";
  62725. break;
  62726. case 3:
  62727. log += "linear\n";
  62728. break;
  62729. }
  62730. }
  62731. //Physics
  62732. if (parsedData.physicsEnabled) {
  62733. var physicsPlugin;
  62734. if (parsedData.physicsEngine === "cannon") {
  62735. physicsPlugin = new BABYLON.CannonJSPlugin();
  62736. }
  62737. else if (parsedData.physicsEngine === "oimo") {
  62738. physicsPlugin = new BABYLON.OimoJSPlugin();
  62739. }
  62740. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  62741. //else - default engine, which is currently oimo
  62742. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  62743. scene.enablePhysics(physicsGravity, physicsPlugin);
  62744. }
  62745. // Metadata
  62746. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  62747. scene.metadata = parsedData.metadata;
  62748. }
  62749. //collisions, if defined. otherwise, default is true
  62750. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  62751. scene.collisionsEnabled = parsedData.collisionsEnabled;
  62752. }
  62753. scene.workerCollisions = !!parsedData.workerCollisions;
  62754. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  62755. if (!container) {
  62756. return false;
  62757. }
  62758. if (parsedData.autoAnimate) {
  62759. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  62760. }
  62761. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  62762. scene.setActiveCameraByID(parsedData.activeCameraID);
  62763. }
  62764. // Environment texture
  62765. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  62766. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  62767. if (parsedData.createDefaultSkybox === true) {
  62768. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  62769. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  62770. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  62771. }
  62772. }
  62773. // Finish
  62774. return true;
  62775. }
  62776. catch (err) {
  62777. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  62778. if (onError) {
  62779. onError(msg, err);
  62780. }
  62781. else {
  62782. BABYLON.Tools.Log(msg);
  62783. throw err;
  62784. }
  62785. }
  62786. finally {
  62787. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  62788. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  62789. }
  62790. }
  62791. return false;
  62792. },
  62793. loadAssetContainer: function (scene, data, rootUrl, onError) {
  62794. var container = loadAssetContainer(scene, data, rootUrl, onError);
  62795. return container;
  62796. }
  62797. });
  62798. })(BABYLON || (BABYLON = {}));
  62799. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  62800. "use strict";
  62801. var BABYLON;
  62802. (function (BABYLON) {
  62803. var FilesInput = /** @class */ (function () {
  62804. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  62805. this.onProcessFileCallback = function () { return true; };
  62806. this._engine = engine;
  62807. this._currentScene = scene;
  62808. this._sceneLoadedCallback = sceneLoadedCallback;
  62809. this._progressCallback = progressCallback;
  62810. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  62811. this._textureLoadingCallback = textureLoadingCallback;
  62812. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  62813. this._onReloadCallback = onReloadCallback;
  62814. this._errorCallback = errorCallback;
  62815. }
  62816. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  62817. var _this = this;
  62818. if (elementToMonitor) {
  62819. this._elementToMonitor = elementToMonitor;
  62820. this._dragEnterHandler = function (e) { _this.drag(e); };
  62821. this._dragOverHandler = function (e) { _this.drag(e); };
  62822. this._dropHandler = function (e) { _this.drop(e); };
  62823. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  62824. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  62825. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  62826. }
  62827. };
  62828. FilesInput.prototype.dispose = function () {
  62829. if (!this._elementToMonitor) {
  62830. return;
  62831. }
  62832. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  62833. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  62834. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  62835. };
  62836. FilesInput.prototype.renderFunction = function () {
  62837. if (this._additionalRenderLoopLogicCallback) {
  62838. this._additionalRenderLoopLogicCallback();
  62839. }
  62840. if (this._currentScene) {
  62841. if (this._textureLoadingCallback) {
  62842. var remaining = this._currentScene.getWaitingItemsCount();
  62843. if (remaining > 0) {
  62844. this._textureLoadingCallback(remaining);
  62845. }
  62846. }
  62847. this._currentScene.render();
  62848. }
  62849. };
  62850. FilesInput.prototype.drag = function (e) {
  62851. e.stopPropagation();
  62852. e.preventDefault();
  62853. };
  62854. FilesInput.prototype.drop = function (eventDrop) {
  62855. eventDrop.stopPropagation();
  62856. eventDrop.preventDefault();
  62857. this.loadFiles(eventDrop);
  62858. };
  62859. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  62860. var _this = this;
  62861. var reader = folder.createReader();
  62862. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  62863. reader.readEntries(function (entries) {
  62864. remaining.count += entries.length;
  62865. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  62866. var entry = entries_1[_i];
  62867. if (entry.isFile) {
  62868. entry.file(function (file) {
  62869. file.correctName = relativePath + file.name;
  62870. files.push(file);
  62871. if (--remaining.count === 0) {
  62872. callback();
  62873. }
  62874. });
  62875. }
  62876. else if (entry.isDirectory) {
  62877. _this._traverseFolder(entry, files, remaining, callback);
  62878. }
  62879. }
  62880. if (--remaining.count) {
  62881. callback();
  62882. }
  62883. });
  62884. };
  62885. FilesInput.prototype._processFiles = function (files) {
  62886. for (var i = 0; i < files.length; i++) {
  62887. var name = files[i].correctName.toLowerCase();
  62888. var extension = name.split('.').pop();
  62889. if (!this.onProcessFileCallback(files[i], name, extension)) {
  62890. continue;
  62891. }
  62892. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  62893. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  62894. this._sceneFileToLoad = files[i];
  62895. }
  62896. else {
  62897. FilesInput.FilesToLoad[name] = files[i];
  62898. }
  62899. }
  62900. };
  62901. FilesInput.prototype.loadFiles = function (event) {
  62902. var _this = this;
  62903. if (this._startingProcessingFilesCallback)
  62904. this._startingProcessingFilesCallback();
  62905. // Handling data transfer via drag'n'drop
  62906. if (event && event.dataTransfer && event.dataTransfer.files) {
  62907. this._filesToLoad = event.dataTransfer.files;
  62908. }
  62909. // Handling files from input files
  62910. if (event && event.target && event.target.files) {
  62911. this._filesToLoad = event.target.files;
  62912. }
  62913. if (this._filesToLoad && this._filesToLoad.length > 0) {
  62914. var files_1 = new Array();
  62915. var folders = [];
  62916. var items = event.dataTransfer ? event.dataTransfer.items : null;
  62917. for (var i = 0; i < this._filesToLoad.length; i++) {
  62918. var fileToLoad = this._filesToLoad[i];
  62919. var name_1 = fileToLoad.name.toLowerCase();
  62920. var entry = void 0;
  62921. fileToLoad.correctName = name_1;
  62922. if (items) {
  62923. var item = items[i];
  62924. if (item.getAsEntry) {
  62925. entry = item.getAsEntry();
  62926. }
  62927. else if (item.webkitGetAsEntry) {
  62928. entry = item.webkitGetAsEntry();
  62929. }
  62930. }
  62931. if (!entry) {
  62932. files_1.push(fileToLoad);
  62933. }
  62934. else {
  62935. if (entry.isDirectory) {
  62936. folders.push(entry);
  62937. }
  62938. else {
  62939. files_1.push(fileToLoad);
  62940. }
  62941. }
  62942. }
  62943. if (folders.length === 0) {
  62944. this._processFiles(files_1);
  62945. this._processReload();
  62946. }
  62947. else {
  62948. var remaining = { count: folders.length };
  62949. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  62950. var folder = folders_1[_i];
  62951. this._traverseFolder(folder, files_1, remaining, function () {
  62952. _this._processFiles(files_1);
  62953. if (remaining.count === 0) {
  62954. _this._processReload();
  62955. }
  62956. });
  62957. }
  62958. }
  62959. }
  62960. };
  62961. FilesInput.prototype._processReload = function () {
  62962. if (this._onReloadCallback) {
  62963. this._onReloadCallback(this._sceneFileToLoad);
  62964. }
  62965. else {
  62966. this.reload();
  62967. }
  62968. };
  62969. FilesInput.prototype.reload = function () {
  62970. var _this = this;
  62971. // If a scene file has been provided
  62972. if (this._sceneFileToLoad) {
  62973. if (this._currentScene) {
  62974. if (BABYLON.Tools.errorsCount > 0) {
  62975. BABYLON.Tools.ClearLogCache();
  62976. }
  62977. this._engine.stopRenderLoop();
  62978. this._currentScene.dispose();
  62979. }
  62980. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  62981. if (_this._progressCallback) {
  62982. _this._progressCallback(progress);
  62983. }
  62984. }).then(function (scene) {
  62985. _this._currentScene = scene;
  62986. if (_this._sceneLoadedCallback) {
  62987. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  62988. }
  62989. // Wait for textures and shaders to be ready
  62990. _this._currentScene.executeWhenReady(function () {
  62991. _this._engine.runRenderLoop(function () {
  62992. _this.renderFunction();
  62993. });
  62994. });
  62995. }).catch(function (error) {
  62996. if (_this._errorCallback) {
  62997. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  62998. }
  62999. });
  63000. }
  63001. else {
  63002. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  63003. }
  63004. };
  63005. FilesInput.FilesToLoad = {};
  63006. return FilesInput;
  63007. }());
  63008. BABYLON.FilesInput = FilesInput;
  63009. })(BABYLON || (BABYLON = {}));
  63010. //# sourceMappingURL=babylon.filesInput.js.map
  63011. "use strict";
  63012. var BABYLON;
  63013. (function (BABYLON) {
  63014. /**
  63015. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63016. * The underlying implementation relies on an associative array to ensure the best performances.
  63017. * The value can be anything including 'null' but except 'undefined'
  63018. */
  63019. var StringDictionary = /** @class */ (function () {
  63020. function StringDictionary() {
  63021. this._count = 0;
  63022. this._data = {};
  63023. }
  63024. /**
  63025. * This will clear this dictionary and copy the content from the 'source' one.
  63026. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63027. * @param source the dictionary to take the content from and copy to this dictionary
  63028. */
  63029. StringDictionary.prototype.copyFrom = function (source) {
  63030. var _this = this;
  63031. this.clear();
  63032. source.forEach(function (t, v) { return _this.add(t, v); });
  63033. };
  63034. /**
  63035. * Get a value based from its key
  63036. * @param key the given key to get the matching value from
  63037. * @return the value if found, otherwise undefined is returned
  63038. */
  63039. StringDictionary.prototype.get = function (key) {
  63040. var val = this._data[key];
  63041. if (val !== undefined) {
  63042. return val;
  63043. }
  63044. return undefined;
  63045. };
  63046. /**
  63047. * Get a value from its key or add it if it doesn't exist.
  63048. * This method will ensure you that a given key/data will be present in the dictionary.
  63049. * @param key the given key to get the matching value from
  63050. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63051. * The factory will only be invoked if there's no data for the given key.
  63052. * @return the value corresponding to the key.
  63053. */
  63054. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63055. var val = this.get(key);
  63056. if (val !== undefined) {
  63057. return val;
  63058. }
  63059. val = factory(key);
  63060. if (val) {
  63061. this.add(key, val);
  63062. }
  63063. return val;
  63064. };
  63065. /**
  63066. * Get a value from its key if present in the dictionary otherwise add it
  63067. * @param key the key to get the value from
  63068. * @param val if there's no such key/value pair in the dictionary add it with this value
  63069. * @return the value corresponding to the key
  63070. */
  63071. StringDictionary.prototype.getOrAdd = function (key, val) {
  63072. var curVal = this.get(key);
  63073. if (curVal !== undefined) {
  63074. return curVal;
  63075. }
  63076. this.add(key, val);
  63077. return val;
  63078. };
  63079. /**
  63080. * Check if there's a given key in the dictionary
  63081. * @param key the key to check for
  63082. * @return true if the key is present, false otherwise
  63083. */
  63084. StringDictionary.prototype.contains = function (key) {
  63085. return this._data[key] !== undefined;
  63086. };
  63087. /**
  63088. * Add a new key and its corresponding value
  63089. * @param key the key to add
  63090. * @param value the value corresponding to the key
  63091. * @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
  63092. */
  63093. StringDictionary.prototype.add = function (key, value) {
  63094. if (this._data[key] !== undefined) {
  63095. return false;
  63096. }
  63097. this._data[key] = value;
  63098. ++this._count;
  63099. return true;
  63100. };
  63101. StringDictionary.prototype.set = function (key, value) {
  63102. if (this._data[key] === undefined) {
  63103. return false;
  63104. }
  63105. this._data[key] = value;
  63106. return true;
  63107. };
  63108. /**
  63109. * Get the element of the given key and remove it from the dictionary
  63110. * @param key
  63111. */
  63112. StringDictionary.prototype.getAndRemove = function (key) {
  63113. var val = this.get(key);
  63114. if (val !== undefined) {
  63115. delete this._data[key];
  63116. --this._count;
  63117. return val;
  63118. }
  63119. return null;
  63120. };
  63121. /**
  63122. * Remove a key/value from the dictionary.
  63123. * @param key the key to remove
  63124. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63125. */
  63126. StringDictionary.prototype.remove = function (key) {
  63127. if (this.contains(key)) {
  63128. delete this._data[key];
  63129. --this._count;
  63130. return true;
  63131. }
  63132. return false;
  63133. };
  63134. /**
  63135. * Clear the whole content of the dictionary
  63136. */
  63137. StringDictionary.prototype.clear = function () {
  63138. this._data = {};
  63139. this._count = 0;
  63140. };
  63141. Object.defineProperty(StringDictionary.prototype, "count", {
  63142. get: function () {
  63143. return this._count;
  63144. },
  63145. enumerable: true,
  63146. configurable: true
  63147. });
  63148. /**
  63149. * Execute a callback on each key/val of the dictionary.
  63150. * Note that you can remove any element in this dictionary in the callback implementation
  63151. * @param callback the callback to execute on a given key/value pair
  63152. */
  63153. StringDictionary.prototype.forEach = function (callback) {
  63154. for (var cur in this._data) {
  63155. var val = this._data[cur];
  63156. callback(cur, val);
  63157. }
  63158. };
  63159. /**
  63160. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63161. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63162. * Note that you can remove any element in this dictionary in the callback implementation
  63163. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63164. */
  63165. StringDictionary.prototype.first = function (callback) {
  63166. for (var cur in this._data) {
  63167. var val = this._data[cur];
  63168. var res = callback(cur, val);
  63169. if (res) {
  63170. return res;
  63171. }
  63172. }
  63173. return null;
  63174. };
  63175. return StringDictionary;
  63176. }());
  63177. BABYLON.StringDictionary = StringDictionary;
  63178. })(BABYLON || (BABYLON = {}));
  63179. //# sourceMappingURL=babylon.stringDictionary.js.map
  63180. "use strict";
  63181. var BABYLON;
  63182. (function (BABYLON) {
  63183. var Tags = /** @class */ (function () {
  63184. function Tags() {
  63185. }
  63186. Tags.EnableFor = function (obj) {
  63187. obj._tags = obj._tags || {};
  63188. obj.hasTags = function () {
  63189. return Tags.HasTags(obj);
  63190. };
  63191. obj.addTags = function (tagsString) {
  63192. return Tags.AddTagsTo(obj, tagsString);
  63193. };
  63194. obj.removeTags = function (tagsString) {
  63195. return Tags.RemoveTagsFrom(obj, tagsString);
  63196. };
  63197. obj.matchesTagsQuery = function (tagsQuery) {
  63198. return Tags.MatchesQuery(obj, tagsQuery);
  63199. };
  63200. };
  63201. Tags.DisableFor = function (obj) {
  63202. delete obj._tags;
  63203. delete obj.hasTags;
  63204. delete obj.addTags;
  63205. delete obj.removeTags;
  63206. delete obj.matchesTagsQuery;
  63207. };
  63208. Tags.HasTags = function (obj) {
  63209. if (!obj._tags) {
  63210. return false;
  63211. }
  63212. return !BABYLON.Tools.IsEmpty(obj._tags);
  63213. };
  63214. Tags.GetTags = function (obj, asString) {
  63215. if (asString === void 0) { asString = true; }
  63216. if (!obj._tags) {
  63217. return null;
  63218. }
  63219. if (asString) {
  63220. var tagsArray = [];
  63221. for (var tag in obj._tags) {
  63222. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  63223. tagsArray.push(tag);
  63224. }
  63225. }
  63226. return tagsArray.join(" ");
  63227. }
  63228. else {
  63229. return obj._tags;
  63230. }
  63231. };
  63232. // the tags 'true' and 'false' are reserved and cannot be used as tags
  63233. // a tag cannot start with '||', '&&', and '!'
  63234. // it cannot contain whitespaces
  63235. Tags.AddTagsTo = function (obj, tagsString) {
  63236. if (!tagsString) {
  63237. return;
  63238. }
  63239. if (typeof tagsString !== "string") {
  63240. return;
  63241. }
  63242. var tags = tagsString.split(" ");
  63243. tags.forEach(function (tag, index, array) {
  63244. Tags._AddTagTo(obj, tag);
  63245. });
  63246. };
  63247. Tags._AddTagTo = function (obj, tag) {
  63248. tag = tag.trim();
  63249. if (tag === "" || tag === "true" || tag === "false") {
  63250. return;
  63251. }
  63252. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  63253. return;
  63254. }
  63255. Tags.EnableFor(obj);
  63256. obj._tags[tag] = true;
  63257. };
  63258. Tags.RemoveTagsFrom = function (obj, tagsString) {
  63259. if (!Tags.HasTags(obj)) {
  63260. return;
  63261. }
  63262. var tags = tagsString.split(" ");
  63263. for (var t in tags) {
  63264. Tags._RemoveTagFrom(obj, tags[t]);
  63265. }
  63266. };
  63267. Tags._RemoveTagFrom = function (obj, tag) {
  63268. delete obj._tags[tag];
  63269. };
  63270. Tags.MatchesQuery = function (obj, tagsQuery) {
  63271. if (tagsQuery === undefined) {
  63272. return true;
  63273. }
  63274. if (tagsQuery === "") {
  63275. return Tags.HasTags(obj);
  63276. }
  63277. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  63278. };
  63279. return Tags;
  63280. }());
  63281. BABYLON.Tags = Tags;
  63282. })(BABYLON || (BABYLON = {}));
  63283. //# sourceMappingURL=babylon.tags.js.map
  63284. "use strict";
  63285. var BABYLON;
  63286. (function (BABYLON) {
  63287. var AndOrNotEvaluator = /** @class */ (function () {
  63288. function AndOrNotEvaluator() {
  63289. }
  63290. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  63291. if (!query.match(/\([^\(\)]*\)/g)) {
  63292. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  63293. }
  63294. else {
  63295. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  63296. // remove parenthesis
  63297. r = r.slice(1, r.length - 1);
  63298. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  63299. });
  63300. }
  63301. if (query === "true") {
  63302. return true;
  63303. }
  63304. if (query === "false") {
  63305. return false;
  63306. }
  63307. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  63308. };
  63309. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  63310. evaluateCallback = evaluateCallback || (function (r) {
  63311. return r === "true" ? true : false;
  63312. });
  63313. var result;
  63314. var or = parenthesisContent.split("||");
  63315. for (var i in or) {
  63316. if (or.hasOwnProperty(i)) {
  63317. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  63318. var and = ori.split("&&");
  63319. if (and.length > 1) {
  63320. for (var j = 0; j < and.length; ++j) {
  63321. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  63322. if (andj !== "true" && andj !== "false") {
  63323. if (andj[0] === "!") {
  63324. result = !evaluateCallback(andj.substring(1));
  63325. }
  63326. else {
  63327. result = evaluateCallback(andj);
  63328. }
  63329. }
  63330. else {
  63331. result = andj === "true" ? true : false;
  63332. }
  63333. if (!result) {
  63334. ori = "false";
  63335. break;
  63336. }
  63337. }
  63338. }
  63339. if (result || ori === "true") {
  63340. result = true;
  63341. break;
  63342. }
  63343. // result equals false (or undefined)
  63344. if (ori !== "true" && ori !== "false") {
  63345. if (ori[0] === "!") {
  63346. result = !evaluateCallback(ori.substring(1));
  63347. }
  63348. else {
  63349. result = evaluateCallback(ori);
  63350. }
  63351. }
  63352. else {
  63353. result = ori === "true" ? true : false;
  63354. }
  63355. }
  63356. }
  63357. // the whole parenthesis scope is replaced by 'true' or 'false'
  63358. return result ? "true" : "false";
  63359. };
  63360. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  63361. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  63362. // remove whitespaces
  63363. r = r.replace(/[\s]/g, function () { return ""; });
  63364. return r.length % 2 ? "!" : "";
  63365. });
  63366. booleanString = booleanString.trim();
  63367. if (booleanString === "!true") {
  63368. booleanString = "false";
  63369. }
  63370. else if (booleanString === "!false") {
  63371. booleanString = "true";
  63372. }
  63373. return booleanString;
  63374. };
  63375. return AndOrNotEvaluator;
  63376. }());
  63377. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  63378. })(BABYLON || (BABYLON = {}));
  63379. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  63380. "use strict";
  63381. var BABYLON;
  63382. (function (BABYLON) {
  63383. var Database = /** @class */ (function () {
  63384. function Database(urlToScene, callbackManifestChecked) {
  63385. // Handling various flavors of prefixed version of IndexedDB
  63386. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  63387. this.callbackManifestChecked = callbackManifestChecked;
  63388. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  63389. this.db = null;
  63390. this._enableSceneOffline = false;
  63391. this._enableTexturesOffline = false;
  63392. this.manifestVersionFound = 0;
  63393. this.mustUpdateRessources = false;
  63394. this.hasReachedQuota = false;
  63395. if (!Database.IDBStorageEnabled) {
  63396. this.callbackManifestChecked(true);
  63397. }
  63398. else {
  63399. this.checkManifestFile();
  63400. }
  63401. }
  63402. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  63403. get: function () {
  63404. return this._enableSceneOffline;
  63405. },
  63406. enumerable: true,
  63407. configurable: true
  63408. });
  63409. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  63410. get: function () {
  63411. return this._enableTexturesOffline;
  63412. },
  63413. enumerable: true,
  63414. configurable: true
  63415. });
  63416. Database.prototype.checkManifestFile = function () {
  63417. var _this = this;
  63418. var noManifestFile = function () {
  63419. _this._enableSceneOffline = false;
  63420. _this._enableTexturesOffline = false;
  63421. _this.callbackManifestChecked(false);
  63422. };
  63423. var timeStampUsed = false;
  63424. var manifestURL = this.currentSceneUrl + ".manifest";
  63425. var xhr = new XMLHttpRequest();
  63426. if (navigator.onLine) {
  63427. // Adding a timestamp to by-pass browsers' cache
  63428. timeStampUsed = true;
  63429. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  63430. }
  63431. xhr.open("GET", manifestURL, true);
  63432. xhr.addEventListener("load", function () {
  63433. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63434. try {
  63435. var manifestFile = JSON.parse(xhr.response);
  63436. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  63437. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  63438. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  63439. _this.manifestVersionFound = manifestFile.version;
  63440. }
  63441. if (_this.callbackManifestChecked) {
  63442. _this.callbackManifestChecked(true);
  63443. }
  63444. }
  63445. catch (ex) {
  63446. noManifestFile();
  63447. }
  63448. }
  63449. else {
  63450. noManifestFile();
  63451. }
  63452. }, false);
  63453. xhr.addEventListener("error", function (event) {
  63454. if (timeStampUsed) {
  63455. timeStampUsed = false;
  63456. // Let's retry without the timeStamp
  63457. // It could fail when coupled with HTML5 Offline API
  63458. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  63459. xhr.open("GET", retryManifestURL, true);
  63460. xhr.send();
  63461. }
  63462. else {
  63463. noManifestFile();
  63464. }
  63465. }, false);
  63466. try {
  63467. xhr.send();
  63468. }
  63469. catch (ex) {
  63470. BABYLON.Tools.Error("Error on XHR send request.");
  63471. this.callbackManifestChecked(false);
  63472. }
  63473. };
  63474. Database.prototype.openAsync = function (successCallback, errorCallback) {
  63475. var _this = this;
  63476. var handleError = function () {
  63477. _this.isSupported = false;
  63478. if (errorCallback)
  63479. errorCallback();
  63480. };
  63481. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  63482. // Your browser doesn't support IndexedDB
  63483. this.isSupported = false;
  63484. if (errorCallback)
  63485. errorCallback();
  63486. }
  63487. else {
  63488. // If the DB hasn't been opened or created yet
  63489. if (!this.db) {
  63490. this.hasReachedQuota = false;
  63491. this.isSupported = true;
  63492. var request = this.idbFactory.open("babylonjs", 1);
  63493. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  63494. request.onerror = function (event) {
  63495. handleError();
  63496. };
  63497. // executes when a version change transaction cannot complete due to other active transactions
  63498. request.onblocked = function (event) {
  63499. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  63500. handleError();
  63501. };
  63502. // DB has been opened successfully
  63503. request.onsuccess = function (event) {
  63504. _this.db = request.result;
  63505. successCallback();
  63506. };
  63507. // Initialization of the DB. Creating Scenes & Textures stores
  63508. request.onupgradeneeded = function (event) {
  63509. _this.db = (event.target).result;
  63510. if (_this.db) {
  63511. try {
  63512. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  63513. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  63514. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  63515. }
  63516. catch (ex) {
  63517. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  63518. handleError();
  63519. }
  63520. }
  63521. };
  63522. }
  63523. else {
  63524. if (successCallback)
  63525. successCallback();
  63526. }
  63527. }
  63528. };
  63529. Database.prototype.loadImageFromDB = function (url, image) {
  63530. var _this = this;
  63531. var completeURL = Database.ReturnFullUrlLocation(url);
  63532. var saveAndLoadImage = function () {
  63533. if (!_this.hasReachedQuota && _this.db !== null) {
  63534. // the texture is not yet in the DB, let's try to save it
  63535. _this._saveImageIntoDBAsync(completeURL, image);
  63536. }
  63537. else {
  63538. image.src = url;
  63539. }
  63540. };
  63541. if (!this.mustUpdateRessources) {
  63542. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  63543. }
  63544. else {
  63545. saveAndLoadImage();
  63546. }
  63547. };
  63548. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  63549. if (this.isSupported && this.db !== null) {
  63550. var texture;
  63551. var transaction = this.db.transaction(["textures"]);
  63552. transaction.onabort = function (event) {
  63553. image.src = url;
  63554. };
  63555. transaction.oncomplete = function (event) {
  63556. var blobTextureURL;
  63557. if (texture) {
  63558. var URL = window.URL || window.webkitURL;
  63559. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  63560. image.onerror = function () {
  63561. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  63562. image.src = url;
  63563. };
  63564. image.src = blobTextureURL;
  63565. }
  63566. else {
  63567. notInDBCallback();
  63568. }
  63569. };
  63570. var getRequest = transaction.objectStore("textures").get(url);
  63571. getRequest.onsuccess = function (event) {
  63572. texture = (event.target).result;
  63573. };
  63574. getRequest.onerror = function (event) {
  63575. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  63576. image.src = url;
  63577. };
  63578. }
  63579. else {
  63580. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63581. image.src = url;
  63582. }
  63583. };
  63584. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  63585. var _this = this;
  63586. if (this.isSupported) {
  63587. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  63588. var generateBlobUrl = function () {
  63589. var blobTextureURL;
  63590. if (blob) {
  63591. var URL = window.URL || window.webkitURL;
  63592. try {
  63593. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  63594. }
  63595. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  63596. catch (ex) {
  63597. blobTextureURL = URL.createObjectURL(blob);
  63598. }
  63599. }
  63600. if (blobTextureURL) {
  63601. image.src = blobTextureURL;
  63602. }
  63603. };
  63604. if (Database.IsUASupportingBlobStorage) {
  63605. var xhr = new XMLHttpRequest(), blob;
  63606. xhr.open("GET", url, true);
  63607. xhr.responseType = "blob";
  63608. xhr.addEventListener("load", function () {
  63609. if (xhr.status === 200 && _this.db) {
  63610. // Blob as response (XHR2)
  63611. blob = xhr.response;
  63612. var transaction = _this.db.transaction(["textures"], "readwrite");
  63613. // the transaction could abort because of a QuotaExceededError error
  63614. transaction.onabort = function (event) {
  63615. try {
  63616. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63617. var srcElement = (event.srcElement || event.target);
  63618. var error = srcElement.error;
  63619. if (error && error.name === "QuotaExceededError") {
  63620. _this.hasReachedQuota = true;
  63621. }
  63622. }
  63623. catch (ex) { }
  63624. generateBlobUrl();
  63625. };
  63626. transaction.oncomplete = function (event) {
  63627. generateBlobUrl();
  63628. };
  63629. var newTexture = { textureUrl: url, data: blob };
  63630. try {
  63631. // Put the blob into the dabase
  63632. var addRequest = transaction.objectStore("textures").put(newTexture);
  63633. addRequest.onsuccess = function (event) {
  63634. };
  63635. addRequest.onerror = function (event) {
  63636. generateBlobUrl();
  63637. };
  63638. }
  63639. catch (ex) {
  63640. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  63641. if (ex.code === 25) {
  63642. Database.IsUASupportingBlobStorage = false;
  63643. }
  63644. image.src = url;
  63645. }
  63646. }
  63647. else {
  63648. image.src = url;
  63649. }
  63650. }, false);
  63651. xhr.addEventListener("error", function (event) {
  63652. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  63653. image.src = url;
  63654. }, false);
  63655. xhr.send();
  63656. }
  63657. else {
  63658. image.src = url;
  63659. }
  63660. }
  63661. else {
  63662. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63663. image.src = url;
  63664. }
  63665. };
  63666. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  63667. var _this = this;
  63668. var updateVersion = function () {
  63669. // the version is not yet in the DB or we need to update it
  63670. _this._saveVersionIntoDBAsync(url, versionLoaded);
  63671. };
  63672. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  63673. };
  63674. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  63675. var _this = this;
  63676. if (this.isSupported && this.db) {
  63677. var version;
  63678. try {
  63679. var transaction = this.db.transaction(["versions"]);
  63680. transaction.oncomplete = function (event) {
  63681. if (version) {
  63682. // If the version in the JSON file is > than the version in DB
  63683. if (_this.manifestVersionFound > version.data) {
  63684. _this.mustUpdateRessources = true;
  63685. updateInDBCallback();
  63686. }
  63687. else {
  63688. callback(version.data);
  63689. }
  63690. }
  63691. else {
  63692. _this.mustUpdateRessources = true;
  63693. updateInDBCallback();
  63694. }
  63695. };
  63696. transaction.onabort = function (event) {
  63697. callback(-1);
  63698. };
  63699. var getRequest = transaction.objectStore("versions").get(url);
  63700. getRequest.onsuccess = function (event) {
  63701. version = (event.target).result;
  63702. };
  63703. getRequest.onerror = function (event) {
  63704. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  63705. callback(-1);
  63706. };
  63707. }
  63708. catch (ex) {
  63709. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  63710. callback(-1);
  63711. }
  63712. }
  63713. else {
  63714. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63715. callback(-1);
  63716. }
  63717. };
  63718. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  63719. var _this = this;
  63720. if (this.isSupported && !this.hasReachedQuota && this.db) {
  63721. try {
  63722. // Open a transaction to the database
  63723. var transaction = this.db.transaction(["versions"], "readwrite");
  63724. // the transaction could abort because of a QuotaExceededError error
  63725. transaction.onabort = function (event) {
  63726. try {
  63727. var error = event.srcElement['error'];
  63728. if (error && error.name === "QuotaExceededError") {
  63729. _this.hasReachedQuota = true;
  63730. }
  63731. }
  63732. catch (ex) { }
  63733. callback(-1);
  63734. };
  63735. transaction.oncomplete = function (event) {
  63736. callback(_this.manifestVersionFound);
  63737. };
  63738. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  63739. // Put the scene into the database
  63740. var addRequest = transaction.objectStore("versions").put(newVersion);
  63741. addRequest.onsuccess = function (event) {
  63742. };
  63743. addRequest.onerror = function (event) {
  63744. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  63745. };
  63746. }
  63747. catch (ex) {
  63748. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  63749. callback(-1);
  63750. }
  63751. }
  63752. else {
  63753. callback(-1);
  63754. }
  63755. };
  63756. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  63757. var _this = this;
  63758. var completeUrl = Database.ReturnFullUrlLocation(url);
  63759. var saveAndLoadFile = function () {
  63760. // the scene is not yet in the DB, let's try to save it
  63761. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  63762. };
  63763. this._checkVersionFromDB(completeUrl, function (version) {
  63764. if (version !== -1) {
  63765. if (!_this.mustUpdateRessources) {
  63766. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  63767. }
  63768. else {
  63769. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  63770. }
  63771. }
  63772. else {
  63773. if (errorCallback) {
  63774. errorCallback();
  63775. }
  63776. }
  63777. });
  63778. };
  63779. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  63780. if (this.isSupported && this.db) {
  63781. var targetStore;
  63782. if (url.indexOf(".babylon") !== -1) {
  63783. targetStore = "scenes";
  63784. }
  63785. else {
  63786. targetStore = "textures";
  63787. }
  63788. var file;
  63789. var transaction = this.db.transaction([targetStore]);
  63790. transaction.oncomplete = function (event) {
  63791. if (file) {
  63792. callback(file.data);
  63793. }
  63794. else {
  63795. notInDBCallback();
  63796. }
  63797. };
  63798. transaction.onabort = function (event) {
  63799. notInDBCallback();
  63800. };
  63801. var getRequest = transaction.objectStore(targetStore).get(url);
  63802. getRequest.onsuccess = function (event) {
  63803. file = (event.target).result;
  63804. };
  63805. getRequest.onerror = function (event) {
  63806. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  63807. notInDBCallback();
  63808. };
  63809. }
  63810. else {
  63811. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63812. callback();
  63813. }
  63814. };
  63815. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  63816. var _this = this;
  63817. if (this.isSupported) {
  63818. var targetStore;
  63819. if (url.indexOf(".babylon") !== -1) {
  63820. targetStore = "scenes";
  63821. }
  63822. else {
  63823. targetStore = "textures";
  63824. }
  63825. // Create XHR
  63826. var xhr = new XMLHttpRequest();
  63827. var fileData;
  63828. xhr.open("GET", url, true);
  63829. if (useArrayBuffer) {
  63830. xhr.responseType = "arraybuffer";
  63831. }
  63832. if (progressCallback) {
  63833. xhr.onprogress = progressCallback;
  63834. }
  63835. xhr.addEventListener("load", function () {
  63836. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  63837. // Blob as response (XHR2)
  63838. //fileData = xhr.responseText;
  63839. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  63840. if (!_this.hasReachedQuota && _this.db) {
  63841. // Open a transaction to the database
  63842. var transaction = _this.db.transaction([targetStore], "readwrite");
  63843. // the transaction could abort because of a QuotaExceededError error
  63844. transaction.onabort = function (event) {
  63845. try {
  63846. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  63847. var error = event.srcElement['error'];
  63848. if (error && error.name === "QuotaExceededError") {
  63849. _this.hasReachedQuota = true;
  63850. }
  63851. }
  63852. catch (ex) { }
  63853. callback(fileData);
  63854. };
  63855. transaction.oncomplete = function (event) {
  63856. callback(fileData);
  63857. };
  63858. var newFile;
  63859. if (targetStore === "scenes") {
  63860. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  63861. }
  63862. else {
  63863. newFile = { textureUrl: url, data: fileData };
  63864. }
  63865. try {
  63866. // Put the scene into the database
  63867. var addRequest = transaction.objectStore(targetStore).put(newFile);
  63868. addRequest.onsuccess = function (event) {
  63869. };
  63870. addRequest.onerror = function (event) {
  63871. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  63872. };
  63873. }
  63874. catch (ex) {
  63875. callback(fileData);
  63876. }
  63877. }
  63878. else {
  63879. callback(fileData);
  63880. }
  63881. }
  63882. else {
  63883. callback();
  63884. }
  63885. }, false);
  63886. xhr.addEventListener("error", function (event) {
  63887. BABYLON.Tools.Error("error on XHR request.");
  63888. callback();
  63889. }, false);
  63890. xhr.send();
  63891. }
  63892. else {
  63893. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  63894. callback();
  63895. }
  63896. };
  63897. Database.IsUASupportingBlobStorage = true;
  63898. Database.IDBStorageEnabled = true;
  63899. Database.parseURL = function (url) {
  63900. var a = document.createElement('a');
  63901. a.href = url;
  63902. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  63903. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  63904. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  63905. return absLocation;
  63906. };
  63907. Database.ReturnFullUrlLocation = function (url) {
  63908. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  63909. return (Database.parseURL(window.location.href) + url);
  63910. }
  63911. else {
  63912. return url;
  63913. }
  63914. };
  63915. return Database;
  63916. }());
  63917. BABYLON.Database = Database;
  63918. })(BABYLON || (BABYLON = {}));
  63919. //# sourceMappingURL=babylon.database.js.map
  63920. "use strict";
  63921. var BABYLON;
  63922. (function (BABYLON) {
  63923. var FresnelParameters = /** @class */ (function () {
  63924. function FresnelParameters() {
  63925. this._isEnabled = true;
  63926. this.leftColor = BABYLON.Color3.White();
  63927. this.rightColor = BABYLON.Color3.Black();
  63928. this.bias = 0;
  63929. this.power = 1;
  63930. }
  63931. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  63932. get: function () {
  63933. return this._isEnabled;
  63934. },
  63935. set: function (value) {
  63936. if (this._isEnabled === value) {
  63937. return;
  63938. }
  63939. this._isEnabled = value;
  63940. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  63941. },
  63942. enumerable: true,
  63943. configurable: true
  63944. });
  63945. FresnelParameters.prototype.clone = function () {
  63946. var newFresnelParameters = new FresnelParameters();
  63947. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  63948. return newFresnelParameters;
  63949. };
  63950. FresnelParameters.prototype.serialize = function () {
  63951. var serializationObject = {};
  63952. serializationObject.isEnabled = this.isEnabled;
  63953. serializationObject.leftColor = this.leftColor;
  63954. serializationObject.rightColor = this.rightColor;
  63955. serializationObject.bias = this.bias;
  63956. serializationObject.power = this.power;
  63957. return serializationObject;
  63958. };
  63959. FresnelParameters.Parse = function (parsedFresnelParameters) {
  63960. var fresnelParameters = new FresnelParameters();
  63961. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  63962. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  63963. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  63964. fresnelParameters.bias = parsedFresnelParameters.bias;
  63965. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  63966. return fresnelParameters;
  63967. };
  63968. return FresnelParameters;
  63969. }());
  63970. BABYLON.FresnelParameters = FresnelParameters;
  63971. })(BABYLON || (BABYLON = {}));
  63972. //# sourceMappingURL=babylon.fresnelParameters.js.map
  63973. "use strict";
  63974. var BABYLON;
  63975. (function (BABYLON) {
  63976. var MultiMaterial = /** @class */ (function (_super) {
  63977. __extends(MultiMaterial, _super);
  63978. function MultiMaterial(name, scene) {
  63979. var _this = _super.call(this, name, scene, true) || this;
  63980. scene.multiMaterials.push(_this);
  63981. _this.subMaterials = new Array();
  63982. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  63983. return _this;
  63984. }
  63985. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  63986. get: function () {
  63987. return this._subMaterials;
  63988. },
  63989. set: function (value) {
  63990. this._subMaterials = value;
  63991. this._hookArray(value);
  63992. },
  63993. enumerable: true,
  63994. configurable: true
  63995. });
  63996. MultiMaterial.prototype._hookArray = function (array) {
  63997. var _this = this;
  63998. var oldPush = array.push;
  63999. array.push = function () {
  64000. var items = [];
  64001. for (var _i = 0; _i < arguments.length; _i++) {
  64002. items[_i] = arguments[_i];
  64003. }
  64004. var result = oldPush.apply(array, items);
  64005. _this._markAllSubMeshesAsTexturesDirty();
  64006. return result;
  64007. };
  64008. var oldSplice = array.splice;
  64009. array.splice = function (index, deleteCount) {
  64010. var deleted = oldSplice.apply(array, [index, deleteCount]);
  64011. _this._markAllSubMeshesAsTexturesDirty();
  64012. return deleted;
  64013. };
  64014. };
  64015. // Properties
  64016. MultiMaterial.prototype.getSubMaterial = function (index) {
  64017. if (index < 0 || index >= this.subMaterials.length) {
  64018. return this.getScene().defaultMaterial;
  64019. }
  64020. return this.subMaterials[index];
  64021. };
  64022. MultiMaterial.prototype.getActiveTextures = function () {
  64023. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  64024. if (subMaterial) {
  64025. return subMaterial.getActiveTextures();
  64026. }
  64027. else {
  64028. return [];
  64029. }
  64030. }));
  64031. var _a;
  64032. };
  64033. // Methods
  64034. MultiMaterial.prototype.getClassName = function () {
  64035. return "MultiMaterial";
  64036. };
  64037. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  64038. for (var index = 0; index < this.subMaterials.length; index++) {
  64039. var subMaterial = this.subMaterials[index];
  64040. if (subMaterial) {
  64041. if (subMaterial.storeEffectOnSubMeshes) {
  64042. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  64043. return false;
  64044. }
  64045. continue;
  64046. }
  64047. if (!subMaterial.isReady(mesh)) {
  64048. return false;
  64049. }
  64050. }
  64051. }
  64052. return true;
  64053. };
  64054. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  64055. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  64056. for (var index = 0; index < this.subMaterials.length; index++) {
  64057. var subMaterial = null;
  64058. var current = this.subMaterials[index];
  64059. if (cloneChildren && current) {
  64060. subMaterial = current.clone(name + "-" + current.name);
  64061. }
  64062. else {
  64063. subMaterial = this.subMaterials[index];
  64064. }
  64065. newMultiMaterial.subMaterials.push(subMaterial);
  64066. }
  64067. return newMultiMaterial;
  64068. };
  64069. MultiMaterial.prototype.serialize = function () {
  64070. var serializationObject = {};
  64071. serializationObject.name = this.name;
  64072. serializationObject.id = this.id;
  64073. if (BABYLON.Tags) {
  64074. serializationObject.tags = BABYLON.Tags.GetTags(this);
  64075. }
  64076. serializationObject.materials = [];
  64077. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  64078. var subMat = this.subMaterials[matIndex];
  64079. if (subMat) {
  64080. serializationObject.materials.push(subMat.id);
  64081. }
  64082. else {
  64083. serializationObject.materials.push(null);
  64084. }
  64085. }
  64086. return serializationObject;
  64087. };
  64088. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  64089. var scene = this.getScene();
  64090. if (!scene) {
  64091. return;
  64092. }
  64093. var index = scene.multiMaterials.indexOf(this);
  64094. if (index >= 0) {
  64095. scene.multiMaterials.splice(index, 1);
  64096. }
  64097. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  64098. };
  64099. return MultiMaterial;
  64100. }(BABYLON.Material));
  64101. BABYLON.MultiMaterial = MultiMaterial;
  64102. })(BABYLON || (BABYLON = {}));
  64103. //# sourceMappingURL=babylon.multiMaterial.js.map
  64104. "use strict";
  64105. var BABYLON;
  64106. (function (BABYLON) {
  64107. var FreeCameraTouchInput = /** @class */ (function () {
  64108. function FreeCameraTouchInput() {
  64109. this._offsetX = null;
  64110. this._offsetY = null;
  64111. this._pointerPressed = new Array();
  64112. this.touchAngularSensibility = 200000.0;
  64113. this.touchMoveSensibility = 250.0;
  64114. }
  64115. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  64116. var _this = this;
  64117. var previousPosition = null;
  64118. if (this._pointerInput === undefined) {
  64119. this._onLostFocus = function (evt) {
  64120. _this._offsetX = null;
  64121. _this._offsetY = null;
  64122. };
  64123. this._pointerInput = function (p, s) {
  64124. var evt = p.event;
  64125. if (evt.pointerType === "mouse") {
  64126. return;
  64127. }
  64128. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  64129. if (!noPreventDefault) {
  64130. evt.preventDefault();
  64131. }
  64132. _this._pointerPressed.push(evt.pointerId);
  64133. if (_this._pointerPressed.length !== 1) {
  64134. return;
  64135. }
  64136. previousPosition = {
  64137. x: evt.clientX,
  64138. y: evt.clientY
  64139. };
  64140. }
  64141. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  64142. if (!noPreventDefault) {
  64143. evt.preventDefault();
  64144. }
  64145. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64146. if (index === -1) {
  64147. return;
  64148. }
  64149. _this._pointerPressed.splice(index, 1);
  64150. if (index != 0) {
  64151. return;
  64152. }
  64153. previousPosition = null;
  64154. _this._offsetX = null;
  64155. _this._offsetY = null;
  64156. }
  64157. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  64158. if (!noPreventDefault) {
  64159. evt.preventDefault();
  64160. }
  64161. if (!previousPosition) {
  64162. return;
  64163. }
  64164. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64165. if (index != 0) {
  64166. return;
  64167. }
  64168. _this._offsetX = evt.clientX - previousPosition.x;
  64169. _this._offsetY = -(evt.clientY - previousPosition.y);
  64170. }
  64171. };
  64172. }
  64173. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  64174. if (this._onLostFocus) {
  64175. element.addEventListener("blur", this._onLostFocus);
  64176. }
  64177. };
  64178. FreeCameraTouchInput.prototype.detachControl = function (element) {
  64179. if (this._pointerInput && element) {
  64180. if (this._observer) {
  64181. this.camera.getScene().onPointerObservable.remove(this._observer);
  64182. this._observer = null;
  64183. }
  64184. if (this._onLostFocus) {
  64185. element.removeEventListener("blur", this._onLostFocus);
  64186. this._onLostFocus = null;
  64187. }
  64188. this._pointerPressed = [];
  64189. this._offsetX = null;
  64190. this._offsetY = null;
  64191. }
  64192. };
  64193. FreeCameraTouchInput.prototype.checkInputs = function () {
  64194. if (this._offsetX && this._offsetY) {
  64195. var camera = this.camera;
  64196. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  64197. if (this._pointerPressed.length > 1) {
  64198. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  64199. }
  64200. else {
  64201. var speed = camera._computeLocalCameraSpeed();
  64202. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  64203. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  64204. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  64205. }
  64206. }
  64207. };
  64208. FreeCameraTouchInput.prototype.getClassName = function () {
  64209. return "FreeCameraTouchInput";
  64210. };
  64211. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64212. return "touch";
  64213. };
  64214. __decorate([
  64215. BABYLON.serialize()
  64216. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64217. __decorate([
  64218. BABYLON.serialize()
  64219. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64220. return FreeCameraTouchInput;
  64221. }());
  64222. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  64223. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  64224. })(BABYLON || (BABYLON = {}));
  64225. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  64226. "use strict";
  64227. var BABYLON;
  64228. (function (BABYLON) {
  64229. // We're mainly based on the logic defined into the FreeCamera code
  64230. var TouchCamera = /** @class */ (function (_super) {
  64231. __extends(TouchCamera, _super);
  64232. //-- end properties for backward compatibility for inputs
  64233. function TouchCamera(name, position, scene) {
  64234. var _this = _super.call(this, name, position, scene) || this;
  64235. _this.inputs.addTouch();
  64236. _this._setupInputs();
  64237. return _this;
  64238. }
  64239. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  64240. //-- Begin properties for backward compatibility for inputs
  64241. get: function () {
  64242. var touch = this.inputs.attached["touch"];
  64243. if (touch)
  64244. return touch.touchAngularSensibility;
  64245. return 0;
  64246. },
  64247. set: function (value) {
  64248. var touch = this.inputs.attached["touch"];
  64249. if (touch)
  64250. touch.touchAngularSensibility = value;
  64251. },
  64252. enumerable: true,
  64253. configurable: true
  64254. });
  64255. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  64256. get: function () {
  64257. var touch = this.inputs.attached["touch"];
  64258. if (touch)
  64259. return touch.touchMoveSensibility;
  64260. return 0;
  64261. },
  64262. set: function (value) {
  64263. var touch = this.inputs.attached["touch"];
  64264. if (touch)
  64265. touch.touchMoveSensibility = value;
  64266. },
  64267. enumerable: true,
  64268. configurable: true
  64269. });
  64270. TouchCamera.prototype.getClassName = function () {
  64271. return "TouchCamera";
  64272. };
  64273. TouchCamera.prototype._setupInputs = function () {
  64274. var mouse = this.inputs.attached["mouse"];
  64275. if (mouse) {
  64276. mouse.touchEnabled = false;
  64277. }
  64278. };
  64279. return TouchCamera;
  64280. }(BABYLON.FreeCamera));
  64281. BABYLON.TouchCamera = TouchCamera;
  64282. })(BABYLON || (BABYLON = {}));
  64283. //# sourceMappingURL=babylon.touchCamera.js.map
  64284. "use strict";
  64285. var BABYLON;
  64286. (function (BABYLON) {
  64287. var ProceduralTexture = /** @class */ (function (_super) {
  64288. __extends(ProceduralTexture, _super);
  64289. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  64290. if (fallbackTexture === void 0) { fallbackTexture = null; }
  64291. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64292. if (isCube === void 0) { isCube = false; }
  64293. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64294. _this.isCube = isCube;
  64295. _this.isEnabled = true;
  64296. _this._currentRefreshId = -1;
  64297. _this._refreshRate = 1;
  64298. _this._vertexBuffers = {};
  64299. _this._uniforms = new Array();
  64300. _this._samplers = new Array();
  64301. _this._textures = {};
  64302. _this._floats = {};
  64303. _this._floatsArrays = {};
  64304. _this._colors3 = {};
  64305. _this._colors4 = {};
  64306. _this._vectors2 = {};
  64307. _this._vectors3 = {};
  64308. _this._matrices = {};
  64309. _this._fallbackTextureUsed = false;
  64310. scene._proceduralTextures.push(_this);
  64311. _this._engine = scene.getEngine();
  64312. _this.name = name;
  64313. _this.isRenderTarget = true;
  64314. _this._size = size;
  64315. _this._generateMipMaps = generateMipMaps;
  64316. _this.setFragment(fragment);
  64317. _this._fallbackTexture = fallbackTexture;
  64318. if (isCube) {
  64319. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  64320. _this.setFloat("face", 0);
  64321. }
  64322. else {
  64323. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  64324. }
  64325. // VBO
  64326. var vertices = [];
  64327. vertices.push(1, 1);
  64328. vertices.push(-1, 1);
  64329. vertices.push(-1, -1);
  64330. vertices.push(1, -1);
  64331. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64332. _this._createIndexBuffer();
  64333. return _this;
  64334. }
  64335. ProceduralTexture.prototype._createIndexBuffer = function () {
  64336. var engine = this._engine;
  64337. // Indices
  64338. var indices = [];
  64339. indices.push(0);
  64340. indices.push(1);
  64341. indices.push(2);
  64342. indices.push(0);
  64343. indices.push(2);
  64344. indices.push(3);
  64345. this._indexBuffer = engine.createIndexBuffer(indices);
  64346. };
  64347. ProceduralTexture.prototype._rebuild = function () {
  64348. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64349. if (vb) {
  64350. vb._rebuild();
  64351. }
  64352. this._createIndexBuffer();
  64353. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64354. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64355. }
  64356. };
  64357. ProceduralTexture.prototype.reset = function () {
  64358. if (this._effect === undefined) {
  64359. return;
  64360. }
  64361. var engine = this._engine;
  64362. engine._releaseEffect(this._effect);
  64363. };
  64364. ProceduralTexture.prototype.isReady = function () {
  64365. var _this = this;
  64366. var engine = this._engine;
  64367. var shaders;
  64368. if (!this._fragment) {
  64369. return false;
  64370. }
  64371. if (this._fallbackTextureUsed) {
  64372. return true;
  64373. }
  64374. if (this._fragment.fragmentElement !== undefined) {
  64375. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  64376. }
  64377. else {
  64378. shaders = { vertex: "procedural", fragment: this._fragment };
  64379. }
  64380. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  64381. _this.releaseInternalTexture();
  64382. if (_this._fallbackTexture) {
  64383. _this._texture = _this._fallbackTexture._texture;
  64384. if (_this._texture) {
  64385. _this._texture.incrementReferences();
  64386. }
  64387. }
  64388. _this._fallbackTextureUsed = true;
  64389. });
  64390. return this._effect.isReady();
  64391. };
  64392. ProceduralTexture.prototype.resetRefreshCounter = function () {
  64393. this._currentRefreshId = -1;
  64394. };
  64395. ProceduralTexture.prototype.setFragment = function (fragment) {
  64396. this._fragment = fragment;
  64397. };
  64398. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  64399. get: function () {
  64400. return this._refreshRate;
  64401. },
  64402. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64403. set: function (value) {
  64404. this._refreshRate = value;
  64405. this.resetRefreshCounter();
  64406. },
  64407. enumerable: true,
  64408. configurable: true
  64409. });
  64410. ProceduralTexture.prototype._shouldRender = function () {
  64411. if (!this.isEnabled || !this.isReady() || !this._texture) {
  64412. return false;
  64413. }
  64414. if (this._fallbackTextureUsed) {
  64415. return false;
  64416. }
  64417. if (this._currentRefreshId === -1) {
  64418. this._currentRefreshId = 1;
  64419. return true;
  64420. }
  64421. if (this.refreshRate === this._currentRefreshId) {
  64422. this._currentRefreshId = 1;
  64423. return true;
  64424. }
  64425. this._currentRefreshId++;
  64426. return false;
  64427. };
  64428. ProceduralTexture.prototype.getRenderSize = function () {
  64429. return this._size;
  64430. };
  64431. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  64432. if (this._fallbackTextureUsed) {
  64433. return;
  64434. }
  64435. this.releaseInternalTexture();
  64436. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  64437. };
  64438. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  64439. if (this._uniforms.indexOf(uniformName) === -1) {
  64440. this._uniforms.push(uniformName);
  64441. }
  64442. };
  64443. ProceduralTexture.prototype.setTexture = function (name, texture) {
  64444. if (this._samplers.indexOf(name) === -1) {
  64445. this._samplers.push(name);
  64446. }
  64447. this._textures[name] = texture;
  64448. return this;
  64449. };
  64450. ProceduralTexture.prototype.setFloat = function (name, value) {
  64451. this._checkUniform(name);
  64452. this._floats[name] = value;
  64453. return this;
  64454. };
  64455. ProceduralTexture.prototype.setFloats = function (name, value) {
  64456. this._checkUniform(name);
  64457. this._floatsArrays[name] = value;
  64458. return this;
  64459. };
  64460. ProceduralTexture.prototype.setColor3 = function (name, value) {
  64461. this._checkUniform(name);
  64462. this._colors3[name] = value;
  64463. return this;
  64464. };
  64465. ProceduralTexture.prototype.setColor4 = function (name, value) {
  64466. this._checkUniform(name);
  64467. this._colors4[name] = value;
  64468. return this;
  64469. };
  64470. ProceduralTexture.prototype.setVector2 = function (name, value) {
  64471. this._checkUniform(name);
  64472. this._vectors2[name] = value;
  64473. return this;
  64474. };
  64475. ProceduralTexture.prototype.setVector3 = function (name, value) {
  64476. this._checkUniform(name);
  64477. this._vectors3[name] = value;
  64478. return this;
  64479. };
  64480. ProceduralTexture.prototype.setMatrix = function (name, value) {
  64481. this._checkUniform(name);
  64482. this._matrices[name] = value;
  64483. return this;
  64484. };
  64485. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64486. var scene = this.getScene();
  64487. if (!scene) {
  64488. return;
  64489. }
  64490. var engine = this._engine;
  64491. // Render
  64492. engine.enableEffect(this._effect);
  64493. engine.setState(false);
  64494. // Texture
  64495. for (var name in this._textures) {
  64496. this._effect.setTexture(name, this._textures[name]);
  64497. }
  64498. // Float
  64499. for (name in this._floats) {
  64500. this._effect.setFloat(name, this._floats[name]);
  64501. }
  64502. // Floats
  64503. for (name in this._floatsArrays) {
  64504. this._effect.setArray(name, this._floatsArrays[name]);
  64505. }
  64506. // Color3
  64507. for (name in this._colors3) {
  64508. this._effect.setColor3(name, this._colors3[name]);
  64509. }
  64510. // Color4
  64511. for (name in this._colors4) {
  64512. var color = this._colors4[name];
  64513. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  64514. }
  64515. // Vector2
  64516. for (name in this._vectors2) {
  64517. this._effect.setVector2(name, this._vectors2[name]);
  64518. }
  64519. // Vector3
  64520. for (name in this._vectors3) {
  64521. this._effect.setVector3(name, this._vectors3[name]);
  64522. }
  64523. // Matrix
  64524. for (name in this._matrices) {
  64525. this._effect.setMatrix(name, this._matrices[name]);
  64526. }
  64527. if (!this._texture) {
  64528. return;
  64529. }
  64530. if (this.isCube) {
  64531. for (var face = 0; face < 6; face++) {
  64532. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  64533. // VBOs
  64534. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64535. this._effect.setFloat("face", face);
  64536. // Clear
  64537. engine.clear(scene.clearColor, true, true, true);
  64538. // Draw order
  64539. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64540. // Mipmaps
  64541. if (face === 5) {
  64542. engine.generateMipMapsForCubemap(this._texture);
  64543. }
  64544. }
  64545. }
  64546. else {
  64547. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  64548. // VBOs
  64549. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  64550. // Clear
  64551. engine.clear(scene.clearColor, true, true, true);
  64552. // Draw order
  64553. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64554. }
  64555. // Unbind
  64556. engine.unBindFramebuffer(this._texture, this.isCube);
  64557. if (this.onGenerated) {
  64558. this.onGenerated();
  64559. }
  64560. };
  64561. ProceduralTexture.prototype.clone = function () {
  64562. var textureSize = this.getSize();
  64563. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  64564. // Base texture
  64565. newTexture.hasAlpha = this.hasAlpha;
  64566. newTexture.level = this.level;
  64567. // RenderTarget Texture
  64568. newTexture.coordinatesMode = this.coordinatesMode;
  64569. return newTexture;
  64570. };
  64571. ProceduralTexture.prototype.dispose = function () {
  64572. var scene = this.getScene();
  64573. if (!scene) {
  64574. return;
  64575. }
  64576. var index = scene._proceduralTextures.indexOf(this);
  64577. if (index >= 0) {
  64578. scene._proceduralTextures.splice(index, 1);
  64579. }
  64580. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64581. if (vertexBuffer) {
  64582. vertexBuffer.dispose();
  64583. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64584. }
  64585. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  64586. this._indexBuffer = null;
  64587. }
  64588. _super.prototype.dispose.call(this);
  64589. };
  64590. return ProceduralTexture;
  64591. }(BABYLON.Texture));
  64592. BABYLON.ProceduralTexture = ProceduralTexture;
  64593. })(BABYLON || (BABYLON = {}));
  64594. //# sourceMappingURL=babylon.proceduralTexture.js.map
  64595. "use strict";
  64596. var BABYLON;
  64597. (function (BABYLON) {
  64598. var CustomProceduralTexture = /** @class */ (function (_super) {
  64599. __extends(CustomProceduralTexture, _super);
  64600. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  64601. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  64602. _this._animate = true;
  64603. _this._time = 0;
  64604. _this._texturePath = texturePath;
  64605. //Try to load json
  64606. _this.loadJson(texturePath);
  64607. _this.refreshRate = 1;
  64608. return _this;
  64609. }
  64610. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  64611. var _this = this;
  64612. var noConfigFile = function () {
  64613. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  64614. try {
  64615. _this.setFragment(_this._texturePath);
  64616. }
  64617. catch (ex) {
  64618. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  64619. }
  64620. };
  64621. var configFileUrl = jsonUrl + "/config.json";
  64622. var xhr = new XMLHttpRequest();
  64623. xhr.open("GET", configFileUrl, true);
  64624. xhr.addEventListener("load", function () {
  64625. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64626. try {
  64627. _this._config = JSON.parse(xhr.response);
  64628. _this.updateShaderUniforms();
  64629. _this.updateTextures();
  64630. _this.setFragment(_this._texturePath + "/custom");
  64631. _this._animate = _this._config.animate;
  64632. _this.refreshRate = _this._config.refreshrate;
  64633. }
  64634. catch (ex) {
  64635. noConfigFile();
  64636. }
  64637. }
  64638. else {
  64639. noConfigFile();
  64640. }
  64641. }, false);
  64642. xhr.addEventListener("error", function () {
  64643. noConfigFile();
  64644. }, false);
  64645. try {
  64646. xhr.send();
  64647. }
  64648. catch (ex) {
  64649. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  64650. }
  64651. };
  64652. CustomProceduralTexture.prototype.isReady = function () {
  64653. if (!_super.prototype.isReady.call(this)) {
  64654. return false;
  64655. }
  64656. for (var name in this._textures) {
  64657. var texture = this._textures[name];
  64658. if (!texture.isReady()) {
  64659. return false;
  64660. }
  64661. }
  64662. return true;
  64663. };
  64664. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  64665. var scene = this.getScene();
  64666. if (this._animate && scene) {
  64667. this._time += scene.getAnimationRatio() * 0.03;
  64668. this.updateShaderUniforms();
  64669. }
  64670. _super.prototype.render.call(this, useCameraPostProcess);
  64671. };
  64672. CustomProceduralTexture.prototype.updateTextures = function () {
  64673. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  64674. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  64675. }
  64676. };
  64677. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  64678. if (this._config) {
  64679. for (var j = 0; j < this._config.uniforms.length; j++) {
  64680. var uniform = this._config.uniforms[j];
  64681. switch (uniform.type) {
  64682. case "float":
  64683. this.setFloat(uniform.name, uniform.value);
  64684. break;
  64685. case "color3":
  64686. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  64687. break;
  64688. case "color4":
  64689. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  64690. break;
  64691. case "vector2":
  64692. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  64693. break;
  64694. case "vector3":
  64695. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  64696. break;
  64697. }
  64698. }
  64699. }
  64700. this.setFloat("time", this._time);
  64701. };
  64702. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  64703. get: function () {
  64704. return this._animate;
  64705. },
  64706. set: function (value) {
  64707. this._animate = value;
  64708. },
  64709. enumerable: true,
  64710. configurable: true
  64711. });
  64712. return CustomProceduralTexture;
  64713. }(BABYLON.ProceduralTexture));
  64714. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  64715. })(BABYLON || (BABYLON = {}));
  64716. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  64717. "use strict";
  64718. var BABYLON;
  64719. (function (BABYLON) {
  64720. var FreeCameraGamepadInput = /** @class */ (function () {
  64721. function FreeCameraGamepadInput() {
  64722. this.gamepadAngularSensibility = 200;
  64723. this.gamepadMoveSensibility = 40;
  64724. // private members
  64725. this._cameraTransform = BABYLON.Matrix.Identity();
  64726. this._deltaTransform = BABYLON.Vector3.Zero();
  64727. this._vector3 = BABYLON.Vector3.Zero();
  64728. this._vector2 = BABYLON.Vector2.Zero();
  64729. }
  64730. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64731. var _this = this;
  64732. var manager = this.camera.getScene().gamepadManager;
  64733. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64734. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64735. // prioritize XBOX gamepads.
  64736. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64737. _this.gamepad = gamepad;
  64738. }
  64739. }
  64740. });
  64741. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64742. if (_this.gamepad === gamepad) {
  64743. _this.gamepad = null;
  64744. }
  64745. });
  64746. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64747. };
  64748. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  64749. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64750. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64751. this.gamepad = null;
  64752. };
  64753. FreeCameraGamepadInput.prototype.checkInputs = function () {
  64754. if (this.gamepad && this.gamepad.leftStick) {
  64755. var camera = this.camera;
  64756. var LSValues = this.gamepad.leftStick;
  64757. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  64758. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64759. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  64760. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  64761. var RSValues = this.gamepad.rightStick;
  64762. if (RSValues) {
  64763. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  64764. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  64765. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  64766. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  64767. }
  64768. else {
  64769. RSValues = { x: 0, y: 0 };
  64770. }
  64771. if (!camera.rotationQuaternion) {
  64772. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  64773. }
  64774. else {
  64775. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  64776. }
  64777. var speed = camera._computeLocalCameraSpeed() * 50.0;
  64778. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  64779. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  64780. camera.cameraDirection.addInPlace(this._deltaTransform);
  64781. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  64782. camera.cameraRotation.addInPlace(this._vector2);
  64783. }
  64784. };
  64785. FreeCameraGamepadInput.prototype.getClassName = function () {
  64786. return "FreeCameraGamepadInput";
  64787. };
  64788. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  64789. return "gamepad";
  64790. };
  64791. __decorate([
  64792. BABYLON.serialize()
  64793. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  64794. __decorate([
  64795. BABYLON.serialize()
  64796. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64797. return FreeCameraGamepadInput;
  64798. }());
  64799. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  64800. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  64801. })(BABYLON || (BABYLON = {}));
  64802. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  64803. "use strict";
  64804. var BABYLON;
  64805. (function (BABYLON) {
  64806. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  64807. function ArcRotateCameraGamepadInput() {
  64808. this.gamepadRotationSensibility = 80;
  64809. this.gamepadMoveSensibility = 40;
  64810. }
  64811. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  64812. var _this = this;
  64813. var manager = this.camera.getScene().gamepadManager;
  64814. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  64815. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  64816. // prioritize XBOX gamepads.
  64817. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  64818. _this.gamepad = gamepad;
  64819. }
  64820. }
  64821. });
  64822. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  64823. if (_this.gamepad === gamepad) {
  64824. _this.gamepad = null;
  64825. }
  64826. });
  64827. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  64828. };
  64829. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  64830. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  64831. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  64832. this.gamepad = null;
  64833. };
  64834. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  64835. if (this.gamepad) {
  64836. var camera = this.camera;
  64837. var RSValues = this.gamepad.rightStick;
  64838. if (RSValues) {
  64839. if (RSValues.x != 0) {
  64840. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  64841. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  64842. camera.inertialAlphaOffset += normalizedRX;
  64843. }
  64844. }
  64845. if (RSValues.y != 0) {
  64846. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  64847. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  64848. camera.inertialBetaOffset += normalizedRY;
  64849. }
  64850. }
  64851. }
  64852. var LSValues = this.gamepad.leftStick;
  64853. if (LSValues && LSValues.y != 0) {
  64854. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  64855. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  64856. this.camera.inertialRadiusOffset -= normalizedLY;
  64857. }
  64858. }
  64859. }
  64860. };
  64861. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  64862. return "ArcRotateCameraGamepadInput";
  64863. };
  64864. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  64865. return "gamepad";
  64866. };
  64867. __decorate([
  64868. BABYLON.serialize()
  64869. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  64870. __decorate([
  64871. BABYLON.serialize()
  64872. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  64873. return ArcRotateCameraGamepadInput;
  64874. }());
  64875. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  64876. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  64877. })(BABYLON || (BABYLON = {}));
  64878. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  64879. "use strict";
  64880. var BABYLON;
  64881. (function (BABYLON) {
  64882. var GamepadManager = /** @class */ (function () {
  64883. function GamepadManager(_scene) {
  64884. var _this = this;
  64885. this._scene = _scene;
  64886. this._babylonGamepads = [];
  64887. this._oneGamepadConnected = false;
  64888. this._isMonitoring = false;
  64889. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  64890. if (!BABYLON.Tools.IsWindowObjectExist()) {
  64891. this._gamepadEventSupported = false;
  64892. }
  64893. else {
  64894. this._gamepadEventSupported = 'GamepadEvent' in window;
  64895. this._gamepadSupport = (navigator.getGamepads ||
  64896. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  64897. }
  64898. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  64899. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  64900. for (var i in _this._babylonGamepads) {
  64901. var gamepad = _this._babylonGamepads[i];
  64902. if (gamepad && gamepad._isConnected) {
  64903. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  64904. }
  64905. }
  64906. });
  64907. this._onGamepadConnectedEvent = function (evt) {
  64908. var gamepad = evt.gamepad;
  64909. if (gamepad.index in _this._babylonGamepads) {
  64910. if (_this._babylonGamepads[gamepad.index].isConnected) {
  64911. return;
  64912. }
  64913. }
  64914. var newGamepad;
  64915. if (_this._babylonGamepads[gamepad.index]) {
  64916. newGamepad = _this._babylonGamepads[gamepad.index];
  64917. newGamepad.browserGamepad = gamepad;
  64918. newGamepad._isConnected = true;
  64919. }
  64920. else {
  64921. newGamepad = _this._addNewGamepad(gamepad);
  64922. }
  64923. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  64924. _this._startMonitoringGamepads();
  64925. };
  64926. this._onGamepadDisconnectedEvent = function (evt) {
  64927. var gamepad = evt.gamepad;
  64928. // Remove the gamepad from the list of gamepads to monitor.
  64929. for (var i in _this._babylonGamepads) {
  64930. if (_this._babylonGamepads[i].index === gamepad.index) {
  64931. var disconnectedGamepad = _this._babylonGamepads[i];
  64932. disconnectedGamepad._isConnected = false;
  64933. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  64934. break;
  64935. }
  64936. }
  64937. };
  64938. if (this._gamepadSupport) {
  64939. //first add already-connected gamepads
  64940. this._updateGamepadObjects();
  64941. if (this._babylonGamepads.length) {
  64942. this._startMonitoringGamepads();
  64943. }
  64944. // Checking if the gamepad connected event is supported (like in Firefox)
  64945. if (this._gamepadEventSupported) {
  64946. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  64947. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  64948. }
  64949. else {
  64950. this._startMonitoringGamepads();
  64951. }
  64952. }
  64953. }
  64954. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  64955. get: function () {
  64956. return this._babylonGamepads;
  64957. },
  64958. enumerable: true,
  64959. configurable: true
  64960. });
  64961. GamepadManager.prototype.getGamepadByType = function (type) {
  64962. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  64963. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  64964. var gamepad = _a[_i];
  64965. if (gamepad && gamepad.type === type) {
  64966. return gamepad;
  64967. }
  64968. }
  64969. return null;
  64970. };
  64971. GamepadManager.prototype.dispose = function () {
  64972. if (this._gamepadEventSupported) {
  64973. if (this._onGamepadConnectedEvent) {
  64974. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  64975. }
  64976. if (this._onGamepadDisconnectedEvent) {
  64977. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  64978. }
  64979. this._onGamepadConnectedEvent = null;
  64980. this._onGamepadDisconnectedEvent = null;
  64981. }
  64982. this._babylonGamepads.forEach(function (gamepad) {
  64983. gamepad.dispose();
  64984. });
  64985. this.onGamepadConnectedObservable.clear();
  64986. this.onGamepadDisconnectedObservable.clear();
  64987. this._oneGamepadConnected = false;
  64988. this._stopMonitoringGamepads();
  64989. this._babylonGamepads = [];
  64990. };
  64991. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  64992. if (!this._oneGamepadConnected) {
  64993. this._oneGamepadConnected = true;
  64994. }
  64995. var newGamepad;
  64996. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  64997. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  64998. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  64999. }
  65000. else if (gamepad.pose) {
  65001. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  65002. }
  65003. else {
  65004. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  65005. }
  65006. this._babylonGamepads[newGamepad.index] = newGamepad;
  65007. return newGamepad;
  65008. };
  65009. GamepadManager.prototype._startMonitoringGamepads = function () {
  65010. if (!this._isMonitoring) {
  65011. this._isMonitoring = true;
  65012. //back-comp
  65013. if (!this._scene) {
  65014. this._checkGamepadsStatus();
  65015. }
  65016. }
  65017. };
  65018. GamepadManager.prototype._stopMonitoringGamepads = function () {
  65019. this._isMonitoring = false;
  65020. };
  65021. GamepadManager.prototype._checkGamepadsStatus = function () {
  65022. var _this = this;
  65023. // Hack to be compatible Chrome
  65024. this._updateGamepadObjects();
  65025. for (var i in this._babylonGamepads) {
  65026. var gamepad = this._babylonGamepads[i];
  65027. if (!gamepad || !gamepad.isConnected) {
  65028. continue;
  65029. }
  65030. gamepad.update();
  65031. }
  65032. if (this._isMonitoring && !this._scene) {
  65033. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  65034. }
  65035. };
  65036. // This function is called only on Chrome, which does not properly support
  65037. // connection/disconnection events and forces you to recopy again the gamepad object
  65038. GamepadManager.prototype._updateGamepadObjects = function () {
  65039. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  65040. for (var i = 0; i < gamepads.length; i++) {
  65041. if (gamepads[i]) {
  65042. if (!this._babylonGamepads[gamepads[i].index]) {
  65043. var newGamepad = this._addNewGamepad(gamepads[i]);
  65044. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65045. }
  65046. else {
  65047. // Forced to copy again this object for Chrome for unknown reason
  65048. this._babylonGamepads[i].browserGamepad = gamepads[i];
  65049. if (!this._babylonGamepads[i].isConnected) {
  65050. this._babylonGamepads[i]._isConnected = true;
  65051. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  65052. }
  65053. }
  65054. }
  65055. }
  65056. };
  65057. return GamepadManager;
  65058. }());
  65059. BABYLON.GamepadManager = GamepadManager;
  65060. })(BABYLON || (BABYLON = {}));
  65061. //# sourceMappingURL=babylon.gamepadManager.js.map
  65062. "use strict";
  65063. var BABYLON;
  65064. (function (BABYLON) {
  65065. var StickValues = /** @class */ (function () {
  65066. function StickValues(x, y) {
  65067. this.x = x;
  65068. this.y = y;
  65069. }
  65070. return StickValues;
  65071. }());
  65072. BABYLON.StickValues = StickValues;
  65073. var Gamepad = /** @class */ (function () {
  65074. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  65075. if (leftStickX === void 0) { leftStickX = 0; }
  65076. if (leftStickY === void 0) { leftStickY = 1; }
  65077. if (rightStickX === void 0) { rightStickX = 2; }
  65078. if (rightStickY === void 0) { rightStickY = 3; }
  65079. this.id = id;
  65080. this.index = index;
  65081. this.browserGamepad = browserGamepad;
  65082. this._isConnected = true;
  65083. this._invertLeftStickY = false;
  65084. this.type = Gamepad.GAMEPAD;
  65085. this._leftStickAxisX = leftStickX;
  65086. this._leftStickAxisY = leftStickY;
  65087. this._rightStickAxisX = rightStickX;
  65088. this._rightStickAxisY = rightStickY;
  65089. if (this.browserGamepad.axes.length >= 2) {
  65090. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65091. }
  65092. if (this.browserGamepad.axes.length >= 4) {
  65093. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65094. }
  65095. }
  65096. Object.defineProperty(Gamepad.prototype, "isConnected", {
  65097. get: function () {
  65098. return this._isConnected;
  65099. },
  65100. enumerable: true,
  65101. configurable: true
  65102. });
  65103. Gamepad.prototype.onleftstickchanged = function (callback) {
  65104. this._onleftstickchanged = callback;
  65105. };
  65106. Gamepad.prototype.onrightstickchanged = function (callback) {
  65107. this._onrightstickchanged = callback;
  65108. };
  65109. Object.defineProperty(Gamepad.prototype, "leftStick", {
  65110. get: function () {
  65111. return this._leftStick;
  65112. },
  65113. set: function (newValues) {
  65114. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  65115. this._onleftstickchanged(newValues);
  65116. }
  65117. this._leftStick = newValues;
  65118. },
  65119. enumerable: true,
  65120. configurable: true
  65121. });
  65122. Object.defineProperty(Gamepad.prototype, "rightStick", {
  65123. get: function () {
  65124. return this._rightStick;
  65125. },
  65126. set: function (newValues) {
  65127. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  65128. this._onrightstickchanged(newValues);
  65129. }
  65130. this._rightStick = newValues;
  65131. },
  65132. enumerable: true,
  65133. configurable: true
  65134. });
  65135. Gamepad.prototype.update = function () {
  65136. if (this._leftStick) {
  65137. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65138. if (this._invertLeftStickY) {
  65139. this.leftStick.y *= -1;
  65140. }
  65141. }
  65142. if (this._rightStick) {
  65143. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65144. }
  65145. };
  65146. Gamepad.prototype.dispose = function () {
  65147. };
  65148. Gamepad.GAMEPAD = 0;
  65149. Gamepad.GENERIC = 1;
  65150. Gamepad.XBOX = 2;
  65151. Gamepad.POSE_ENABLED = 3;
  65152. return Gamepad;
  65153. }());
  65154. BABYLON.Gamepad = Gamepad;
  65155. var GenericPad = /** @class */ (function (_super) {
  65156. __extends(GenericPad, _super);
  65157. function GenericPad(id, index, browserGamepad) {
  65158. var _this = _super.call(this, id, index, browserGamepad) || this;
  65159. _this.onButtonDownObservable = new BABYLON.Observable();
  65160. _this.onButtonUpObservable = new BABYLON.Observable();
  65161. _this.type = Gamepad.GENERIC;
  65162. _this._buttons = new Array(browserGamepad.buttons.length);
  65163. return _this;
  65164. }
  65165. GenericPad.prototype.onbuttondown = function (callback) {
  65166. this._onbuttondown = callback;
  65167. };
  65168. GenericPad.prototype.onbuttonup = function (callback) {
  65169. this._onbuttonup = callback;
  65170. };
  65171. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  65172. if (newValue !== currentValue) {
  65173. if (newValue === 1) {
  65174. if (this._onbuttondown) {
  65175. this._onbuttondown(buttonIndex);
  65176. }
  65177. this.onButtonDownObservable.notifyObservers(buttonIndex);
  65178. }
  65179. if (newValue === 0) {
  65180. if (this._onbuttonup) {
  65181. this._onbuttonup(buttonIndex);
  65182. }
  65183. this.onButtonUpObservable.notifyObservers(buttonIndex);
  65184. }
  65185. }
  65186. return newValue;
  65187. };
  65188. GenericPad.prototype.update = function () {
  65189. _super.prototype.update.call(this);
  65190. for (var index = 0; index < this._buttons.length; index++) {
  65191. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  65192. }
  65193. };
  65194. GenericPad.prototype.dispose = function () {
  65195. _super.prototype.dispose.call(this);
  65196. this.onButtonDownObservable.clear();
  65197. this.onButtonUpObservable.clear();
  65198. };
  65199. return GenericPad;
  65200. }(Gamepad));
  65201. BABYLON.GenericPad = GenericPad;
  65202. })(BABYLON || (BABYLON = {}));
  65203. //# sourceMappingURL=babylon.gamepad.js.map
  65204. "use strict";
  65205. var BABYLON;
  65206. (function (BABYLON) {
  65207. var Xbox360Button;
  65208. (function (Xbox360Button) {
  65209. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  65210. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  65211. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  65212. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  65213. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  65214. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  65215. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  65216. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  65217. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  65218. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  65219. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  65220. var Xbox360Dpad;
  65221. (function (Xbox360Dpad) {
  65222. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  65223. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  65224. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  65225. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  65226. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  65227. var Xbox360Pad = /** @class */ (function (_super) {
  65228. __extends(Xbox360Pad, _super);
  65229. function Xbox360Pad(id, index, gamepad, xboxOne) {
  65230. if (xboxOne === void 0) { xboxOne = false; }
  65231. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  65232. _this._leftTrigger = 0;
  65233. _this._rightTrigger = 0;
  65234. _this.onButtonDownObservable = new BABYLON.Observable();
  65235. _this.onButtonUpObservable = new BABYLON.Observable();
  65236. _this.onPadDownObservable = new BABYLON.Observable();
  65237. _this.onPadUpObservable = new BABYLON.Observable();
  65238. _this._buttonA = 0;
  65239. _this._buttonB = 0;
  65240. _this._buttonX = 0;
  65241. _this._buttonY = 0;
  65242. _this._buttonBack = 0;
  65243. _this._buttonStart = 0;
  65244. _this._buttonLB = 0;
  65245. _this._buttonRB = 0;
  65246. _this._buttonLeftStick = 0;
  65247. _this._buttonRightStick = 0;
  65248. _this._dPadUp = 0;
  65249. _this._dPadDown = 0;
  65250. _this._dPadLeft = 0;
  65251. _this._dPadRight = 0;
  65252. _this._isXboxOnePad = false;
  65253. _this.type = BABYLON.Gamepad.XBOX;
  65254. _this._isXboxOnePad = xboxOne;
  65255. return _this;
  65256. }
  65257. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  65258. this._onlefttriggerchanged = callback;
  65259. };
  65260. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  65261. this._onrighttriggerchanged = callback;
  65262. };
  65263. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  65264. get: function () {
  65265. return this._leftTrigger;
  65266. },
  65267. set: function (newValue) {
  65268. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  65269. this._onlefttriggerchanged(newValue);
  65270. }
  65271. this._leftTrigger = newValue;
  65272. },
  65273. enumerable: true,
  65274. configurable: true
  65275. });
  65276. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  65277. get: function () {
  65278. return this._rightTrigger;
  65279. },
  65280. set: function (newValue) {
  65281. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  65282. this._onrighttriggerchanged(newValue);
  65283. }
  65284. this._rightTrigger = newValue;
  65285. },
  65286. enumerable: true,
  65287. configurable: true
  65288. });
  65289. Xbox360Pad.prototype.onbuttondown = function (callback) {
  65290. this._onbuttondown = callback;
  65291. };
  65292. Xbox360Pad.prototype.onbuttonup = function (callback) {
  65293. this._onbuttonup = callback;
  65294. };
  65295. Xbox360Pad.prototype.ondpaddown = function (callback) {
  65296. this._ondpaddown = callback;
  65297. };
  65298. Xbox360Pad.prototype.ondpadup = function (callback) {
  65299. this._ondpadup = callback;
  65300. };
  65301. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  65302. if (newValue !== currentValue) {
  65303. if (newValue === 1) {
  65304. if (this._onbuttondown) {
  65305. this._onbuttondown(buttonType);
  65306. }
  65307. this.onButtonDownObservable.notifyObservers(buttonType);
  65308. }
  65309. if (newValue === 0) {
  65310. if (this._onbuttonup) {
  65311. this._onbuttonup(buttonType);
  65312. }
  65313. this.onButtonUpObservable.notifyObservers(buttonType);
  65314. }
  65315. }
  65316. return newValue;
  65317. };
  65318. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  65319. if (newValue !== currentValue) {
  65320. if (newValue === 1) {
  65321. if (this._ondpaddown) {
  65322. this._ondpaddown(buttonType);
  65323. }
  65324. this.onPadDownObservable.notifyObservers(buttonType);
  65325. }
  65326. if (newValue === 0) {
  65327. if (this._ondpadup) {
  65328. this._ondpadup(buttonType);
  65329. }
  65330. this.onPadUpObservable.notifyObservers(buttonType);
  65331. }
  65332. }
  65333. return newValue;
  65334. };
  65335. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  65336. get: function () {
  65337. return this._buttonA;
  65338. },
  65339. set: function (value) {
  65340. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  65341. },
  65342. enumerable: true,
  65343. configurable: true
  65344. });
  65345. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  65346. get: function () {
  65347. return this._buttonB;
  65348. },
  65349. set: function (value) {
  65350. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  65351. },
  65352. enumerable: true,
  65353. configurable: true
  65354. });
  65355. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  65356. get: function () {
  65357. return this._buttonX;
  65358. },
  65359. set: function (value) {
  65360. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  65361. },
  65362. enumerable: true,
  65363. configurable: true
  65364. });
  65365. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  65366. get: function () {
  65367. return this._buttonY;
  65368. },
  65369. set: function (value) {
  65370. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  65371. },
  65372. enumerable: true,
  65373. configurable: true
  65374. });
  65375. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  65376. get: function () {
  65377. return this._buttonStart;
  65378. },
  65379. set: function (value) {
  65380. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  65381. },
  65382. enumerable: true,
  65383. configurable: true
  65384. });
  65385. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  65386. get: function () {
  65387. return this._buttonBack;
  65388. },
  65389. set: function (value) {
  65390. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  65391. },
  65392. enumerable: true,
  65393. configurable: true
  65394. });
  65395. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  65396. get: function () {
  65397. return this._buttonLB;
  65398. },
  65399. set: function (value) {
  65400. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  65401. },
  65402. enumerable: true,
  65403. configurable: true
  65404. });
  65405. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  65406. get: function () {
  65407. return this._buttonRB;
  65408. },
  65409. set: function (value) {
  65410. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  65411. },
  65412. enumerable: true,
  65413. configurable: true
  65414. });
  65415. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  65416. get: function () {
  65417. return this._buttonLeftStick;
  65418. },
  65419. set: function (value) {
  65420. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  65421. },
  65422. enumerable: true,
  65423. configurable: true
  65424. });
  65425. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  65426. get: function () {
  65427. return this._buttonRightStick;
  65428. },
  65429. set: function (value) {
  65430. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  65431. },
  65432. enumerable: true,
  65433. configurable: true
  65434. });
  65435. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  65436. get: function () {
  65437. return this._dPadUp;
  65438. },
  65439. set: function (value) {
  65440. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  65441. },
  65442. enumerable: true,
  65443. configurable: true
  65444. });
  65445. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  65446. get: function () {
  65447. return this._dPadDown;
  65448. },
  65449. set: function (value) {
  65450. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  65451. },
  65452. enumerable: true,
  65453. configurable: true
  65454. });
  65455. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  65456. get: function () {
  65457. return this._dPadLeft;
  65458. },
  65459. set: function (value) {
  65460. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  65461. },
  65462. enumerable: true,
  65463. configurable: true
  65464. });
  65465. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  65466. get: function () {
  65467. return this._dPadRight;
  65468. },
  65469. set: function (value) {
  65470. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  65471. },
  65472. enumerable: true,
  65473. configurable: true
  65474. });
  65475. Xbox360Pad.prototype.update = function () {
  65476. _super.prototype.update.call(this);
  65477. if (this._isXboxOnePad) {
  65478. this.buttonA = this.browserGamepad.buttons[0].value;
  65479. this.buttonB = this.browserGamepad.buttons[1].value;
  65480. this.buttonX = this.browserGamepad.buttons[2].value;
  65481. this.buttonY = this.browserGamepad.buttons[3].value;
  65482. this.buttonLB = this.browserGamepad.buttons[4].value;
  65483. this.buttonRB = this.browserGamepad.buttons[5].value;
  65484. this.leftTrigger = this.browserGamepad.axes[2];
  65485. this.rightTrigger = this.browserGamepad.axes[5];
  65486. this.buttonBack = this.browserGamepad.buttons[9].value;
  65487. this.buttonStart = this.browserGamepad.buttons[8].value;
  65488. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  65489. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  65490. this.dPadUp = this.browserGamepad.buttons[11].value;
  65491. this.dPadDown = this.browserGamepad.buttons[12].value;
  65492. this.dPadLeft = this.browserGamepad.buttons[13].value;
  65493. this.dPadRight = this.browserGamepad.buttons[14].value;
  65494. }
  65495. else {
  65496. this.buttonA = this.browserGamepad.buttons[0].value;
  65497. this.buttonB = this.browserGamepad.buttons[1].value;
  65498. this.buttonX = this.browserGamepad.buttons[2].value;
  65499. this.buttonY = this.browserGamepad.buttons[3].value;
  65500. this.buttonLB = this.browserGamepad.buttons[4].value;
  65501. this.buttonRB = this.browserGamepad.buttons[5].value;
  65502. this.leftTrigger = this.browserGamepad.buttons[6].value;
  65503. this.rightTrigger = this.browserGamepad.buttons[7].value;
  65504. this.buttonBack = this.browserGamepad.buttons[8].value;
  65505. this.buttonStart = this.browserGamepad.buttons[9].value;
  65506. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  65507. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  65508. this.dPadUp = this.browserGamepad.buttons[12].value;
  65509. this.dPadDown = this.browserGamepad.buttons[13].value;
  65510. this.dPadLeft = this.browserGamepad.buttons[14].value;
  65511. this.dPadRight = this.browserGamepad.buttons[15].value;
  65512. }
  65513. };
  65514. Xbox360Pad.prototype.dispose = function () {
  65515. _super.prototype.dispose.call(this);
  65516. this.onButtonDownObservable.clear();
  65517. this.onButtonUpObservable.clear();
  65518. this.onPadDownObservable.clear();
  65519. this.onPadUpObservable.clear();
  65520. };
  65521. return Xbox360Pad;
  65522. }(BABYLON.Gamepad));
  65523. BABYLON.Xbox360Pad = Xbox360Pad;
  65524. })(BABYLON || (BABYLON = {}));
  65525. //# sourceMappingURL=babylon.xboxGamepad.js.map
  65526. "use strict";
  65527. var BABYLON;
  65528. (function (BABYLON) {
  65529. var PoseEnabledControllerType;
  65530. (function (PoseEnabledControllerType) {
  65531. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  65532. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  65533. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  65534. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  65535. /**
  65536. * Google Daydream
  65537. */
  65538. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  65539. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  65540. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  65541. var PoseEnabledControllerHelper = /** @class */ (function () {
  65542. function PoseEnabledControllerHelper() {
  65543. }
  65544. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  65545. // Oculus Touch
  65546. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  65547. return new BABYLON.OculusTouchController(vrGamepad);
  65548. }
  65549. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  65550. return new BABYLON.WindowsMotionController(vrGamepad);
  65551. }
  65552. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  65553. return new BABYLON.ViveController(vrGamepad);
  65554. }
  65555. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  65556. return new BABYLON.GearVRController(vrGamepad);
  65557. }
  65558. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  65559. return new BABYLON.DaydreamController(vrGamepad);
  65560. }
  65561. else {
  65562. return new BABYLON.GenericController(vrGamepad);
  65563. }
  65564. };
  65565. return PoseEnabledControllerHelper;
  65566. }());
  65567. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  65568. var PoseEnabledController = /** @class */ (function (_super) {
  65569. __extends(PoseEnabledController, _super);
  65570. function PoseEnabledController(browserGamepad) {
  65571. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  65572. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  65573. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  65574. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  65575. // Represents device position and rotation in babylon space
  65576. _this.devicePosition = BABYLON.Vector3.Zero();
  65577. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65578. _this.deviceScaleFactor = 1;
  65579. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  65580. _this._deviceToWorld = BABYLON.Matrix.Identity();
  65581. /**
  65582. * Node to be used when casting a ray from the controller
  65583. */
  65584. _this._pointingPoseNode = null;
  65585. _this._workingMatrix = BABYLON.Matrix.Identity();
  65586. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  65587. _this.controllerType = PoseEnabledControllerType.GENERIC;
  65588. _this.position = BABYLON.Vector3.Zero();
  65589. _this.rotationQuaternion = new BABYLON.Quaternion();
  65590. _this._calculatedPosition = BABYLON.Vector3.Zero();
  65591. _this._calculatedRotation = new BABYLON.Quaternion();
  65592. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  65593. return _this;
  65594. }
  65595. PoseEnabledController.prototype.update = function () {
  65596. _super.prototype.update.call(this);
  65597. var pose = this.browserGamepad.pose;
  65598. this.updateFromDevice(pose);
  65599. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  65600. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  65601. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  65602. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  65603. if (this._mesh) {
  65604. this._mesh.position.copyFrom(this.devicePosition);
  65605. if (this._mesh.rotationQuaternion) {
  65606. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65607. }
  65608. }
  65609. };
  65610. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  65611. if (poseData) {
  65612. this.rawPose = poseData;
  65613. if (poseData.position) {
  65614. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  65615. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  65616. this._deviceRoomPosition.z *= -1;
  65617. }
  65618. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  65619. this._calculatedPosition.addInPlace(this.position);
  65620. }
  65621. var pose = this.rawPose;
  65622. if (poseData.orientation && pose.orientation) {
  65623. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  65624. if (this._mesh) {
  65625. if (this._mesh.getScene().useRightHandedSystem) {
  65626. this._deviceRoomRotationQuaternion.z *= -1;
  65627. this._deviceRoomRotationQuaternion.w *= -1;
  65628. }
  65629. else {
  65630. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  65631. }
  65632. }
  65633. // if the camera is set, rotate to the camera's rotation
  65634. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  65635. }
  65636. }
  65637. };
  65638. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  65639. if (this._mesh) {
  65640. this._mesh.parent = null;
  65641. }
  65642. this._mesh = mesh;
  65643. if (this._poseControlledCamera) {
  65644. this._mesh.parent = this._poseControlledCamera;
  65645. }
  65646. if (!this._mesh.rotationQuaternion) {
  65647. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  65648. }
  65649. };
  65650. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  65651. this._poseControlledCamera = camera;
  65652. if (this._mesh) {
  65653. this._mesh.parent = this._poseControlledCamera;
  65654. }
  65655. };
  65656. PoseEnabledController.prototype.dispose = function () {
  65657. if (this._mesh) {
  65658. this._mesh.dispose();
  65659. }
  65660. this._mesh = null;
  65661. _super.prototype.dispose.call(this);
  65662. };
  65663. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  65664. get: function () {
  65665. return this._mesh;
  65666. },
  65667. enumerable: true,
  65668. configurable: true
  65669. });
  65670. PoseEnabledController.prototype.getForwardRay = function (length) {
  65671. if (length === void 0) { length = 100; }
  65672. if (!this.mesh) {
  65673. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  65674. }
  65675. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  65676. var origin = m.getTranslation();
  65677. var forward = new BABYLON.Vector3(0, 0, -1);
  65678. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65679. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65680. return new BABYLON.Ray(origin, direction, length);
  65681. };
  65682. /**
  65683. * Name of the child mesh that can be used to cast a ray from the controller
  65684. */
  65685. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  65686. return PoseEnabledController;
  65687. }(BABYLON.Gamepad));
  65688. BABYLON.PoseEnabledController = PoseEnabledController;
  65689. })(BABYLON || (BABYLON = {}));
  65690. //# sourceMappingURL=babylon.poseEnabledController.js.map
  65691. "use strict";
  65692. var BABYLON;
  65693. (function (BABYLON) {
  65694. var WebVRController = /** @class */ (function (_super) {
  65695. __extends(WebVRController, _super);
  65696. function WebVRController(vrGamepad) {
  65697. var _this = _super.call(this, vrGamepad) || this;
  65698. // Observables
  65699. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  65700. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  65701. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  65702. _this.onPadStateChangedObservable = new BABYLON.Observable();
  65703. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  65704. _this.pad = { x: 0, y: 0 };
  65705. // avoid GC, store state in a tmp object
  65706. _this._changes = {
  65707. pressChanged: false,
  65708. touchChanged: false,
  65709. valueChanged: false,
  65710. changed: false
  65711. };
  65712. _this._buttons = new Array(vrGamepad.buttons.length);
  65713. _this.hand = vrGamepad.hand;
  65714. return _this;
  65715. }
  65716. WebVRController.prototype.onButtonStateChange = function (callback) {
  65717. this._onButtonStateChange = callback;
  65718. };
  65719. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  65720. get: function () {
  65721. return this._defaultModel;
  65722. },
  65723. enumerable: true,
  65724. configurable: true
  65725. });
  65726. WebVRController.prototype.update = function () {
  65727. _super.prototype.update.call(this);
  65728. for (var index = 0; index < this._buttons.length; index++) {
  65729. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  65730. }
  65731. ;
  65732. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  65733. this.pad.x = this.leftStick.x;
  65734. this.pad.y = this.leftStick.y;
  65735. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  65736. }
  65737. };
  65738. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  65739. if (!newState) {
  65740. newState = {
  65741. pressed: false,
  65742. touched: false,
  65743. value: 0
  65744. };
  65745. }
  65746. if (!currentState) {
  65747. this._buttons[buttonIndex] = {
  65748. pressed: newState.pressed,
  65749. touched: newState.touched,
  65750. value: newState.value
  65751. };
  65752. return;
  65753. }
  65754. this._checkChanges(newState, currentState);
  65755. if (this._changes.changed) {
  65756. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  65757. this._handleButtonChange(buttonIndex, newState, this._changes);
  65758. }
  65759. this._buttons[buttonIndex].pressed = newState.pressed;
  65760. this._buttons[buttonIndex].touched = newState.touched;
  65761. // oculus triggers are never 0, thou not touched.
  65762. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  65763. };
  65764. WebVRController.prototype._checkChanges = function (newState, currentState) {
  65765. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  65766. this._changes.touchChanged = newState.touched !== currentState.touched;
  65767. this._changes.valueChanged = newState.value !== currentState.value;
  65768. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  65769. return this._changes;
  65770. };
  65771. WebVRController.prototype.dispose = function () {
  65772. _super.prototype.dispose.call(this);
  65773. this.onTriggerStateChangedObservable.clear();
  65774. this.onMainButtonStateChangedObservable.clear();
  65775. this.onSecondaryButtonStateChangedObservable.clear();
  65776. this.onPadStateChangedObservable.clear();
  65777. this.onPadValuesChangedObservable.clear();
  65778. };
  65779. return WebVRController;
  65780. }(BABYLON.PoseEnabledController));
  65781. BABYLON.WebVRController = WebVRController;
  65782. })(BABYLON || (BABYLON = {}));
  65783. //# sourceMappingURL=babylon.webVRController.js.map
  65784. "use strict";
  65785. var BABYLON;
  65786. (function (BABYLON) {
  65787. var OculusTouchController = /** @class */ (function (_super) {
  65788. __extends(OculusTouchController, _super);
  65789. function OculusTouchController(vrGamepad) {
  65790. var _this = _super.call(this, vrGamepad) || this;
  65791. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  65792. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  65793. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  65794. return _this;
  65795. }
  65796. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65797. var _this = this;
  65798. var meshName;
  65799. // Hand
  65800. if (this.hand === 'left') {
  65801. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  65802. }
  65803. else {
  65804. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  65805. }
  65806. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  65807. /*
  65808. Parent Mesh name: oculus_touch_left
  65809. - body
  65810. - trigger
  65811. - thumbstick
  65812. - grip
  65813. - button_y
  65814. - button_x
  65815. - button_enter
  65816. */
  65817. _this._defaultModel = newMeshes[1];
  65818. _this.attachToMesh(_this._defaultModel);
  65819. if (meshLoaded) {
  65820. meshLoaded(_this._defaultModel);
  65821. }
  65822. });
  65823. };
  65824. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  65825. // helper getters for left and right hand.
  65826. get: function () {
  65827. if (this.hand === 'right') {
  65828. return this.onMainButtonStateChangedObservable;
  65829. }
  65830. else {
  65831. throw new Error('No A button on left hand');
  65832. }
  65833. },
  65834. enumerable: true,
  65835. configurable: true
  65836. });
  65837. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  65838. get: function () {
  65839. if (this.hand === 'right') {
  65840. return this.onSecondaryButtonStateChangedObservable;
  65841. }
  65842. else {
  65843. throw new Error('No B button on left hand');
  65844. }
  65845. },
  65846. enumerable: true,
  65847. configurable: true
  65848. });
  65849. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  65850. get: function () {
  65851. if (this.hand === 'left') {
  65852. return this.onMainButtonStateChangedObservable;
  65853. }
  65854. else {
  65855. throw new Error('No X button on right hand');
  65856. }
  65857. },
  65858. enumerable: true,
  65859. configurable: true
  65860. });
  65861. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  65862. get: function () {
  65863. if (this.hand === 'left') {
  65864. return this.onSecondaryButtonStateChangedObservable;
  65865. }
  65866. else {
  65867. throw new Error('No Y button on right hand');
  65868. }
  65869. },
  65870. enumerable: true,
  65871. configurable: true
  65872. });
  65873. /*
  65874. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  65875. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  65876. 2) secondary trigger (same)
  65877. 3) A (right) X (left), touch, pressed = value
  65878. 4) B / Y
  65879. 5) thumb rest
  65880. */
  65881. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65882. var notifyObject = state; //{ state: state, changes: changes };
  65883. var triggerDirection = this.hand === 'right' ? -1 : 1;
  65884. switch (buttonIdx) {
  65885. case 0:
  65886. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  65887. return;
  65888. case 1:// index trigger
  65889. if (this._defaultModel) {
  65890. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  65891. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  65892. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  65893. }
  65894. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  65895. return;
  65896. case 2:// secondary trigger
  65897. if (this._defaultModel) {
  65898. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  65899. }
  65900. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  65901. return;
  65902. case 3:
  65903. if (this._defaultModel) {
  65904. if (notifyObject.pressed) {
  65905. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  65906. }
  65907. else {
  65908. (this._defaultModel.getChildren()[1]).position.y = 0;
  65909. }
  65910. }
  65911. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  65912. return;
  65913. case 4:
  65914. if (this._defaultModel) {
  65915. if (notifyObject.pressed) {
  65916. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  65917. }
  65918. else {
  65919. (this._defaultModel.getChildren()[2]).position.y = 0;
  65920. }
  65921. }
  65922. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  65923. return;
  65924. case 5:
  65925. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  65926. return;
  65927. }
  65928. };
  65929. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  65930. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  65931. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  65932. return OculusTouchController;
  65933. }(BABYLON.WebVRController));
  65934. BABYLON.OculusTouchController = OculusTouchController;
  65935. })(BABYLON || (BABYLON = {}));
  65936. //# sourceMappingURL=babylon.oculusTouchController.js.map
  65937. "use strict";
  65938. var BABYLON;
  65939. (function (BABYLON) {
  65940. var ViveController = /** @class */ (function (_super) {
  65941. __extends(ViveController, _super);
  65942. function ViveController(vrGamepad) {
  65943. var _this = _super.call(this, vrGamepad) || this;
  65944. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  65945. _this._invertLeftStickY = true;
  65946. return _this;
  65947. }
  65948. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65949. var _this = this;
  65950. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  65951. /*
  65952. Parent Mesh name: ViveWand
  65953. - body
  65954. - r_gripper
  65955. - l_gripper
  65956. - menu_button
  65957. - system_button
  65958. - trackpad
  65959. - trigger
  65960. - LED
  65961. */
  65962. _this._defaultModel = newMeshes[1];
  65963. _this.attachToMesh(_this._defaultModel);
  65964. if (meshLoaded) {
  65965. meshLoaded(_this._defaultModel);
  65966. }
  65967. });
  65968. };
  65969. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  65970. get: function () {
  65971. return this.onMainButtonStateChangedObservable;
  65972. },
  65973. enumerable: true,
  65974. configurable: true
  65975. });
  65976. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  65977. get: function () {
  65978. return this.onMainButtonStateChangedObservable;
  65979. },
  65980. enumerable: true,
  65981. configurable: true
  65982. });
  65983. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  65984. get: function () {
  65985. return this.onSecondaryButtonStateChangedObservable;
  65986. },
  65987. enumerable: true,
  65988. configurable: true
  65989. });
  65990. /**
  65991. * Vive mapping:
  65992. * 0: touchpad
  65993. * 1: trigger
  65994. * 2: left AND right buttons
  65995. * 3: menu button
  65996. */
  65997. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  65998. var notifyObject = state; //{ state: state, changes: changes };
  65999. switch (buttonIdx) {
  66000. case 0:
  66001. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66002. return;
  66003. case 1:// index trigger
  66004. if (this._defaultModel) {
  66005. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  66006. }
  66007. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66008. return;
  66009. case 2:// left AND right button
  66010. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66011. return;
  66012. case 3:
  66013. if (this._defaultModel) {
  66014. if (notifyObject.pressed) {
  66015. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66016. }
  66017. else {
  66018. (this._defaultModel.getChildren()[2]).position.y = 0;
  66019. }
  66020. }
  66021. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66022. return;
  66023. }
  66024. };
  66025. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  66026. ViveController.MODEL_FILENAME = 'wand.babylon';
  66027. return ViveController;
  66028. }(BABYLON.WebVRController));
  66029. BABYLON.ViveController = ViveController;
  66030. })(BABYLON || (BABYLON = {}));
  66031. //# sourceMappingURL=babylon.viveController.js.map
  66032. "use strict";
  66033. var BABYLON;
  66034. (function (BABYLON) {
  66035. var GenericController = /** @class */ (function (_super) {
  66036. __extends(GenericController, _super);
  66037. function GenericController(vrGamepad) {
  66038. return _super.call(this, vrGamepad) || this;
  66039. }
  66040. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66041. var _this = this;
  66042. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  66043. _this._defaultModel = newMeshes[1];
  66044. _this.attachToMesh(_this._defaultModel);
  66045. if (meshLoaded) {
  66046. meshLoaded(_this._defaultModel);
  66047. }
  66048. });
  66049. };
  66050. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66051. console.log("Button id: " + buttonIdx + "state: ");
  66052. console.dir(state);
  66053. };
  66054. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66055. GenericController.MODEL_FILENAME = 'generic.babylon';
  66056. return GenericController;
  66057. }(BABYLON.WebVRController));
  66058. BABYLON.GenericController = GenericController;
  66059. })(BABYLON || (BABYLON = {}));
  66060. //# sourceMappingURL=babylon.genericController.js.map
  66061. "use strict";
  66062. var BABYLON;
  66063. (function (BABYLON) {
  66064. var LoadedMeshInfo = /** @class */ (function () {
  66065. function LoadedMeshInfo() {
  66066. this.buttonMeshes = {};
  66067. this.axisMeshes = {};
  66068. }
  66069. return LoadedMeshInfo;
  66070. }());
  66071. var WindowsMotionController = /** @class */ (function (_super) {
  66072. __extends(WindowsMotionController, _super);
  66073. function WindowsMotionController(vrGamepad) {
  66074. var _this = _super.call(this, vrGamepad) || this;
  66075. _this._mapping = {
  66076. // Semantic button names
  66077. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  66078. // A mapping of the button name to glTF model node name
  66079. // that should be transformed by button value.
  66080. buttonMeshNames: {
  66081. 'trigger': 'SELECT',
  66082. 'menu': 'MENU',
  66083. 'grip': 'GRASP',
  66084. 'thumbstick': 'THUMBSTICK_PRESS',
  66085. 'trackpad': 'TOUCHPAD_PRESS'
  66086. },
  66087. // This mapping is used to translate from the Motion Controller to Babylon semantics
  66088. buttonObservableNames: {
  66089. 'trigger': 'onTriggerStateChangedObservable',
  66090. 'menu': 'onSecondaryButtonStateChangedObservable',
  66091. 'grip': 'onMainButtonStateChangedObservable',
  66092. 'thumbstick': 'onPadStateChangedObservable',
  66093. 'trackpad': 'onTrackpadChangedObservable'
  66094. },
  66095. // A mapping of the axis name to glTF model node name
  66096. // that should be transformed by axis value.
  66097. // This array mirrors the browserGamepad.axes array, such that
  66098. // the mesh corresponding to axis 0 is in this array index 0.
  66099. axisMeshNames: [
  66100. 'THUMBSTICK_X',
  66101. 'THUMBSTICK_Y',
  66102. 'TOUCHPAD_TOUCH_X',
  66103. 'TOUCHPAD_TOUCH_Y'
  66104. ],
  66105. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  66106. };
  66107. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  66108. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  66109. _this.trackpad = { x: 0, y: 0 };
  66110. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  66111. _this._loadedMeshInfo = null;
  66112. return _this;
  66113. }
  66114. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  66115. get: function () {
  66116. return this.onTriggerStateChangedObservable;
  66117. },
  66118. enumerable: true,
  66119. configurable: true
  66120. });
  66121. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  66122. get: function () {
  66123. return this.onSecondaryButtonStateChangedObservable;
  66124. },
  66125. enumerable: true,
  66126. configurable: true
  66127. });
  66128. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  66129. get: function () {
  66130. return this.onMainButtonStateChangedObservable;
  66131. },
  66132. enumerable: true,
  66133. configurable: true
  66134. });
  66135. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  66136. get: function () {
  66137. return this.onPadStateChangedObservable;
  66138. },
  66139. enumerable: true,
  66140. configurable: true
  66141. });
  66142. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  66143. get: function () {
  66144. return this.onTrackpadChangedObservable;
  66145. },
  66146. enumerable: true,
  66147. configurable: true
  66148. });
  66149. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  66150. get: function () {
  66151. return this.onTrackpadValuesChangedObservable;
  66152. },
  66153. enumerable: true,
  66154. configurable: true
  66155. });
  66156. /**
  66157. * Called once per frame by the engine.
  66158. */
  66159. WindowsMotionController.prototype.update = function () {
  66160. _super.prototype.update.call(this);
  66161. if (this.browserGamepad.axes) {
  66162. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  66163. this.trackpad.x = this.browserGamepad["axes"][2];
  66164. this.trackpad.y = this.browserGamepad["axes"][3];
  66165. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  66166. }
  66167. // Only need to animate axes if there is a loaded mesh
  66168. if (this._loadedMeshInfo) {
  66169. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  66170. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  66171. }
  66172. }
  66173. }
  66174. };
  66175. /**
  66176. * Called once for each button that changed state since the last frame
  66177. * @param buttonIdx Which button index changed
  66178. * @param state New state of the button
  66179. * @param changes Which properties on the state changed since last frame
  66180. */
  66181. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66182. var buttonName = this._mapping.buttons[buttonIdx];
  66183. if (!buttonName) {
  66184. return;
  66185. }
  66186. // Only emit events for buttons that we know how to map from index to name
  66187. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  66188. if (observable) {
  66189. observable.notifyObservers(state);
  66190. }
  66191. this.lerpButtonTransform(buttonName, state.value);
  66192. };
  66193. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  66194. // If there is no loaded mesh, there is nothing to transform.
  66195. if (!this._loadedMeshInfo) {
  66196. return;
  66197. }
  66198. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  66199. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66200. return;
  66201. }
  66202. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  66203. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  66204. };
  66205. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  66206. if (!this._loadedMeshInfo) {
  66207. return;
  66208. }
  66209. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  66210. if (!meshInfo) {
  66211. return;
  66212. }
  66213. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66214. return;
  66215. }
  66216. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  66217. var lerpValue = axisValue * 0.5 + 0.5;
  66218. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  66219. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  66220. };
  66221. /**
  66222. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  66223. * @param scene scene in which to add meshes
  66224. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  66225. */
  66226. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  66227. var _this = this;
  66228. if (forceDefault === void 0) { forceDefault = false; }
  66229. var path;
  66230. var filename;
  66231. // Checking if GLB loader is present
  66232. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  66233. // Determine the device specific folder based on the ID suffix
  66234. var device = 'default';
  66235. if (this.id && !forceDefault) {
  66236. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  66237. device = ((match && match[0]) || device);
  66238. }
  66239. // Hand
  66240. if (this.hand === 'left') {
  66241. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  66242. }
  66243. else {
  66244. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  66245. }
  66246. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  66247. }
  66248. else {
  66249. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  66250. path = BABYLON.GenericController.MODEL_BASE_URL;
  66251. filename = BABYLON.GenericController.MODEL_FILENAME;
  66252. }
  66253. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  66254. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  66255. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  66256. if (!_this._loadedMeshInfo) {
  66257. return;
  66258. }
  66259. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  66260. _this.attachToMesh(_this._defaultModel);
  66261. if (meshLoaded) {
  66262. meshLoaded(_this._defaultModel);
  66263. }
  66264. }, null, function (scene, message) {
  66265. BABYLON.Tools.Log(message);
  66266. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  66267. if (!forceDefault) {
  66268. _this.initControllerMesh(scene, meshLoaded, true);
  66269. }
  66270. });
  66271. };
  66272. /**
  66273. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  66274. * can be transformed by button presses and axes values, based on this._mapping.
  66275. *
  66276. * @param scene scene in which the meshes exist
  66277. * @param meshes list of meshes that make up the controller model to process
  66278. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  66279. */
  66280. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  66281. var loadedMeshInfo = null;
  66282. // Create a new mesh to contain the glTF hierarchy
  66283. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  66284. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  66285. var childMesh = null;
  66286. for (var i = 0; i < meshes.length; i++) {
  66287. var mesh = meshes[i];
  66288. if (!mesh.parent) {
  66289. // Exclude controller meshes from picking results
  66290. mesh.isPickable = false;
  66291. // Handle root node, attach to the new parentMesh
  66292. childMesh = mesh;
  66293. break;
  66294. }
  66295. }
  66296. if (childMesh) {
  66297. childMesh.setParent(parentMesh);
  66298. // Create our mesh info. Note that this method will always return non-null.
  66299. loadedMeshInfo = this.createMeshInfo(parentMesh);
  66300. }
  66301. else {
  66302. BABYLON.Tools.Warn('Could not find root node in model file.');
  66303. }
  66304. return loadedMeshInfo;
  66305. };
  66306. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  66307. var loadedMeshInfo = new LoadedMeshInfo();
  66308. var i;
  66309. loadedMeshInfo.rootNode = rootNode;
  66310. // Reset the caches
  66311. loadedMeshInfo.buttonMeshes = {};
  66312. loadedMeshInfo.axisMeshes = {};
  66313. // Button Meshes
  66314. for (i = 0; i < this._mapping.buttons.length; i++) {
  66315. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  66316. if (!buttonMeshName) {
  66317. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  66318. continue;
  66319. }
  66320. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  66321. if (!buttonMesh) {
  66322. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  66323. continue;
  66324. }
  66325. var buttonMeshInfo = {
  66326. index: i,
  66327. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  66328. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  66329. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  66330. };
  66331. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  66332. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  66333. }
  66334. else {
  66335. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  66336. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  66337. '(VALUE: ' + !!buttonMeshInfo.value +
  66338. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  66339. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  66340. ')');
  66341. }
  66342. }
  66343. // Axis Meshes
  66344. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  66345. var axisMeshName = this._mapping.axisMeshNames[i];
  66346. if (!axisMeshName) {
  66347. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  66348. continue;
  66349. }
  66350. var axisMesh = getChildByName(rootNode, axisMeshName);
  66351. if (!axisMesh) {
  66352. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  66353. continue;
  66354. }
  66355. var axisMeshInfo = {
  66356. index: i,
  66357. value: getImmediateChildByName(axisMesh, 'VALUE'),
  66358. min: getImmediateChildByName(axisMesh, 'MIN'),
  66359. max: getImmediateChildByName(axisMesh, 'MAX')
  66360. };
  66361. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  66362. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  66363. }
  66364. else {
  66365. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  66366. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  66367. '(VALUE: ' + !!axisMeshInfo.value +
  66368. ', MIN: ' + !!axisMeshInfo.min +
  66369. ', MAX:' + !!axisMeshInfo.max +
  66370. ')');
  66371. }
  66372. }
  66373. // Pointing Ray
  66374. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  66375. if (!loadedMeshInfo.pointingPoseNode) {
  66376. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  66377. }
  66378. return loadedMeshInfo;
  66379. // Look through all children recursively. This will return null if no mesh exists with the given name.
  66380. function getChildByName(node, name) {
  66381. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  66382. }
  66383. // Look through only immediate children. This will return null if no mesh exists with the given name.
  66384. function getImmediateChildByName(node, name) {
  66385. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  66386. }
  66387. };
  66388. WindowsMotionController.prototype.getForwardRay = function (length) {
  66389. if (length === void 0) { length = 100; }
  66390. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  66391. return _super.prototype.getForwardRay.call(this, length);
  66392. }
  66393. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  66394. var origin = m.getTranslation();
  66395. var forward = new BABYLON.Vector3(0, 0, -1);
  66396. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66397. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66398. return new BABYLON.Ray(origin, direction, length);
  66399. };
  66400. WindowsMotionController.prototype.dispose = function () {
  66401. _super.prototype.dispose.call(this);
  66402. this.onTrackpadChangedObservable.clear();
  66403. };
  66404. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  66405. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  66406. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  66407. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  66408. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  66409. return WindowsMotionController;
  66410. }(BABYLON.WebVRController));
  66411. BABYLON.WindowsMotionController = WindowsMotionController;
  66412. })(BABYLON || (BABYLON = {}));
  66413. //# sourceMappingURL=babylon.windowsMotionController.js.map
  66414. "use strict";
  66415. var BABYLON;
  66416. (function (BABYLON) {
  66417. var GearVRController = /** @class */ (function (_super) {
  66418. __extends(GearVRController, _super);
  66419. function GearVRController(vrGamepad) {
  66420. var _this = _super.call(this, vrGamepad) || this;
  66421. _this._buttonIndexToObservableNameMap = [
  66422. 'onTrackpadChangedObservable',
  66423. 'onTriggerStateChangedObservable' // Trigger
  66424. ];
  66425. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  66426. return _this;
  66427. }
  66428. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66429. var _this = this;
  66430. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  66431. _this._defaultModel = newMeshes[1];
  66432. _this.attachToMesh(_this._defaultModel);
  66433. if (meshLoaded) {
  66434. meshLoaded(_this._defaultModel);
  66435. }
  66436. });
  66437. };
  66438. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66439. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  66440. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  66441. // Only emit events for buttons that we know how to map from index to observable
  66442. var observable = this[observableName];
  66443. if (observable) {
  66444. observable.notifyObservers(state);
  66445. }
  66446. }
  66447. };
  66448. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66449. GearVRController.MODEL_FILENAME = 'generic.babylon';
  66450. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  66451. return GearVRController;
  66452. }(BABYLON.WebVRController));
  66453. BABYLON.GearVRController = GearVRController;
  66454. })(BABYLON || (BABYLON = {}));
  66455. //# sourceMappingURL=babylon.gearVRController.js.map
  66456. "use strict";
  66457. var BABYLON;
  66458. (function (BABYLON) {
  66459. /**
  66460. * Google Daydream controller
  66461. */
  66462. var DaydreamController = /** @class */ (function (_super) {
  66463. __extends(DaydreamController, _super);
  66464. function DaydreamController(vrGamepad) {
  66465. var _this = _super.call(this, vrGamepad) || this;
  66466. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  66467. return _this;
  66468. }
  66469. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66470. var _this = this;
  66471. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  66472. _this._defaultModel = newMeshes[1];
  66473. _this.attachToMesh(_this._defaultModel);
  66474. if (meshLoaded) {
  66475. meshLoaded(_this._defaultModel);
  66476. }
  66477. });
  66478. };
  66479. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66480. // Daydream controller only has 1 GamepadButton (on the trackpad).
  66481. if (buttonIdx === 0) {
  66482. var observable = this.onTriggerStateChangedObservable;
  66483. if (observable) {
  66484. observable.notifyObservers(state);
  66485. }
  66486. }
  66487. else {
  66488. // If the app or home buttons are ever made available
  66489. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  66490. }
  66491. };
  66492. /**
  66493. * Base Url for the controller model.
  66494. */
  66495. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66496. /**
  66497. * File name for the controller model.
  66498. */
  66499. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  66500. /**
  66501. * Gamepad Id prefix used to identify Daydream Controller.
  66502. */
  66503. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  66504. return DaydreamController;
  66505. }(BABYLON.WebVRController));
  66506. BABYLON.DaydreamController = DaydreamController;
  66507. })(BABYLON || (BABYLON = {}));
  66508. //# sourceMappingURL=babylon.daydreamController.js.map
  66509. "use strict";
  66510. var BABYLON;
  66511. (function (BABYLON) {
  66512. var FollowCamera = /** @class */ (function (_super) {
  66513. __extends(FollowCamera, _super);
  66514. function FollowCamera(name, position, scene, lockedTarget) {
  66515. if (lockedTarget === void 0) { lockedTarget = null; }
  66516. var _this = _super.call(this, name, position, scene) || this;
  66517. _this.radius = 12;
  66518. _this.rotationOffset = 0;
  66519. _this.heightOffset = 4;
  66520. _this.cameraAcceleration = 0.05;
  66521. _this.maxCameraSpeed = 20;
  66522. _this.lockedTarget = lockedTarget;
  66523. return _this;
  66524. }
  66525. FollowCamera.prototype.getRadians = function (degrees) {
  66526. return degrees * Math.PI / 180;
  66527. };
  66528. FollowCamera.prototype.follow = function (cameraTarget) {
  66529. if (!cameraTarget)
  66530. return;
  66531. var yRotation;
  66532. if (cameraTarget.rotationQuaternion) {
  66533. var rotMatrix = new BABYLON.Matrix();
  66534. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  66535. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  66536. }
  66537. else {
  66538. yRotation = cameraTarget.rotation.y;
  66539. }
  66540. var radians = this.getRadians(this.rotationOffset) + yRotation;
  66541. var targetPosition = cameraTarget.getAbsolutePosition();
  66542. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  66543. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  66544. var dx = targetX - this.position.x;
  66545. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  66546. var dz = (targetZ) - this.position.z;
  66547. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  66548. var vy = dy * this.cameraAcceleration;
  66549. var vz = dz * this.cameraAcceleration * 2;
  66550. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  66551. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66552. }
  66553. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  66554. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66555. }
  66556. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  66557. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  66558. }
  66559. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  66560. this.setTarget(targetPosition);
  66561. };
  66562. FollowCamera.prototype._checkInputs = function () {
  66563. _super.prototype._checkInputs.call(this);
  66564. if (this.lockedTarget) {
  66565. this.follow(this.lockedTarget);
  66566. }
  66567. };
  66568. FollowCamera.prototype.getClassName = function () {
  66569. return "FollowCamera";
  66570. };
  66571. __decorate([
  66572. BABYLON.serialize()
  66573. ], FollowCamera.prototype, "radius", void 0);
  66574. __decorate([
  66575. BABYLON.serialize()
  66576. ], FollowCamera.prototype, "rotationOffset", void 0);
  66577. __decorate([
  66578. BABYLON.serialize()
  66579. ], FollowCamera.prototype, "heightOffset", void 0);
  66580. __decorate([
  66581. BABYLON.serialize()
  66582. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  66583. __decorate([
  66584. BABYLON.serialize()
  66585. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  66586. __decorate([
  66587. BABYLON.serializeAsMeshReference("lockedTargetId")
  66588. ], FollowCamera.prototype, "lockedTarget", void 0);
  66589. return FollowCamera;
  66590. }(BABYLON.TargetCamera));
  66591. BABYLON.FollowCamera = FollowCamera;
  66592. var ArcFollowCamera = /** @class */ (function (_super) {
  66593. __extends(ArcFollowCamera, _super);
  66594. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  66595. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  66596. _this.alpha = alpha;
  66597. _this.beta = beta;
  66598. _this.radius = radius;
  66599. _this.target = target;
  66600. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  66601. _this.follow();
  66602. return _this;
  66603. }
  66604. ArcFollowCamera.prototype.follow = function () {
  66605. if (!this.target) {
  66606. return;
  66607. }
  66608. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  66609. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  66610. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  66611. var targetPosition = this.target.getAbsolutePosition();
  66612. this.position = targetPosition.add(this._cartesianCoordinates);
  66613. this.setTarget(targetPosition);
  66614. };
  66615. ArcFollowCamera.prototype._checkInputs = function () {
  66616. _super.prototype._checkInputs.call(this);
  66617. this.follow();
  66618. };
  66619. ArcFollowCamera.prototype.getClassName = function () {
  66620. return "ArcFollowCamera";
  66621. };
  66622. return ArcFollowCamera;
  66623. }(BABYLON.TargetCamera));
  66624. BABYLON.ArcFollowCamera = ArcFollowCamera;
  66625. })(BABYLON || (BABYLON = {}));
  66626. //# sourceMappingURL=babylon.followCamera.js.map
  66627. "use strict";
  66628. var BABYLON;
  66629. (function (BABYLON) {
  66630. // We're mainly based on the logic defined into the FreeCamera code
  66631. var UniversalCamera = /** @class */ (function (_super) {
  66632. __extends(UniversalCamera, _super);
  66633. //-- end properties for backward compatibility for inputs
  66634. function UniversalCamera(name, position, scene) {
  66635. var _this = _super.call(this, name, position, scene) || this;
  66636. _this.inputs.addGamepad();
  66637. return _this;
  66638. }
  66639. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  66640. //-- Begin properties for backward compatibility for inputs
  66641. get: function () {
  66642. var gamepad = this.inputs.attached["gamepad"];
  66643. if (gamepad)
  66644. return gamepad.gamepadAngularSensibility;
  66645. return 0;
  66646. },
  66647. set: function (value) {
  66648. var gamepad = this.inputs.attached["gamepad"];
  66649. if (gamepad)
  66650. gamepad.gamepadAngularSensibility = value;
  66651. },
  66652. enumerable: true,
  66653. configurable: true
  66654. });
  66655. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  66656. get: function () {
  66657. var gamepad = this.inputs.attached["gamepad"];
  66658. if (gamepad)
  66659. return gamepad.gamepadMoveSensibility;
  66660. return 0;
  66661. },
  66662. set: function (value) {
  66663. var gamepad = this.inputs.attached["gamepad"];
  66664. if (gamepad)
  66665. gamepad.gamepadMoveSensibility = value;
  66666. },
  66667. enumerable: true,
  66668. configurable: true
  66669. });
  66670. UniversalCamera.prototype.getClassName = function () {
  66671. return "UniversalCamera";
  66672. };
  66673. return UniversalCamera;
  66674. }(BABYLON.TouchCamera));
  66675. BABYLON.UniversalCamera = UniversalCamera;
  66676. })(BABYLON || (BABYLON = {}));
  66677. //# sourceMappingURL=babylon.universalCamera.js.map
  66678. "use strict";
  66679. var BABYLON;
  66680. (function (BABYLON) {
  66681. // We're mainly based on the logic defined into the FreeCamera code
  66682. var GamepadCamera = /** @class */ (function (_super) {
  66683. __extends(GamepadCamera, _super);
  66684. //-- end properties for backward compatibility for inputs
  66685. function GamepadCamera(name, position, scene) {
  66686. return _super.call(this, name, position, scene) || this;
  66687. }
  66688. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  66689. //-- Begin properties for backward compatibility for inputs
  66690. get: function () {
  66691. var gamepad = this.inputs.attached["gamepad"];
  66692. if (gamepad)
  66693. return gamepad.gamepadAngularSensibility;
  66694. return 0;
  66695. },
  66696. set: function (value) {
  66697. var gamepad = this.inputs.attached["gamepad"];
  66698. if (gamepad)
  66699. gamepad.gamepadAngularSensibility = value;
  66700. },
  66701. enumerable: true,
  66702. configurable: true
  66703. });
  66704. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  66705. get: function () {
  66706. var gamepad = this.inputs.attached["gamepad"];
  66707. if (gamepad)
  66708. return gamepad.gamepadMoveSensibility;
  66709. return 0;
  66710. },
  66711. set: function (value) {
  66712. var gamepad = this.inputs.attached["gamepad"];
  66713. if (gamepad)
  66714. gamepad.gamepadMoveSensibility = value;
  66715. },
  66716. enumerable: true,
  66717. configurable: true
  66718. });
  66719. GamepadCamera.prototype.getClassName = function () {
  66720. return "GamepadCamera";
  66721. };
  66722. return GamepadCamera;
  66723. }(BABYLON.UniversalCamera));
  66724. BABYLON.GamepadCamera = GamepadCamera;
  66725. })(BABYLON || (BABYLON = {}));
  66726. //# sourceMappingURL=babylon.gamepadCamera.js.map
  66727. "use strict";
  66728. var BABYLON;
  66729. (function (BABYLON) {
  66730. var PostProcessRenderPipelineManager = /** @class */ (function () {
  66731. function PostProcessRenderPipelineManager() {
  66732. this._renderPipelines = {};
  66733. }
  66734. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  66735. this._renderPipelines[renderPipeline._name] = renderPipeline;
  66736. };
  66737. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  66738. if (unique === void 0) { unique = false; }
  66739. var renderPipeline = this._renderPipelines[renderPipelineName];
  66740. if (!renderPipeline) {
  66741. return;
  66742. }
  66743. renderPipeline._attachCameras(cameras, unique);
  66744. };
  66745. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  66746. var renderPipeline = this._renderPipelines[renderPipelineName];
  66747. if (!renderPipeline) {
  66748. return;
  66749. }
  66750. renderPipeline._detachCameras(cameras);
  66751. };
  66752. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66753. var renderPipeline = this._renderPipelines[renderPipelineName];
  66754. if (!renderPipeline) {
  66755. return;
  66756. }
  66757. renderPipeline._enableEffect(renderEffectName, cameras);
  66758. };
  66759. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  66760. var renderPipeline = this._renderPipelines[renderPipelineName];
  66761. if (!renderPipeline) {
  66762. return;
  66763. }
  66764. renderPipeline._disableEffect(renderEffectName, cameras);
  66765. };
  66766. PostProcessRenderPipelineManager.prototype.update = function () {
  66767. for (var renderPipelineName in this._renderPipelines) {
  66768. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66769. var pipeline = this._renderPipelines[renderPipelineName];
  66770. if (!pipeline.isSupported) {
  66771. pipeline.dispose();
  66772. delete this._renderPipelines[renderPipelineName];
  66773. }
  66774. else {
  66775. pipeline._update();
  66776. }
  66777. }
  66778. }
  66779. };
  66780. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  66781. for (var renderPipelineName in this._renderPipelines) {
  66782. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66783. var pipeline = this._renderPipelines[renderPipelineName];
  66784. pipeline._rebuild();
  66785. }
  66786. }
  66787. };
  66788. PostProcessRenderPipelineManager.prototype.dispose = function () {
  66789. for (var renderPipelineName in this._renderPipelines) {
  66790. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  66791. var pipeline = this._renderPipelines[renderPipelineName];
  66792. pipeline.dispose();
  66793. }
  66794. }
  66795. };
  66796. return PostProcessRenderPipelineManager;
  66797. }());
  66798. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  66799. })(BABYLON || (BABYLON = {}));
  66800. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  66801. "use strict";
  66802. var BABYLON;
  66803. (function (BABYLON) {
  66804. /**
  66805. * This represents a set of one or more post processes in Babylon.
  66806. * A post process can be used to apply a shader to a texture after it is rendered.
  66807. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  66808. */
  66809. var PostProcessRenderEffect = /** @class */ (function () {
  66810. /**
  66811. * Instantiates a post process render effect.
  66812. * A post process can be used to apply a shader to a texture after it is rendered.
  66813. * @param engine The engine the effect is tied to
  66814. * @param name The name of the effect
  66815. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  66816. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  66817. */
  66818. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  66819. this._name = name;
  66820. this._singleInstance = singleInstance || true;
  66821. this._getPostProcesses = getPostProcesses;
  66822. this._cameras = {};
  66823. this._indicesForCamera = {};
  66824. this._postProcesses = {};
  66825. }
  66826. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  66827. /**
  66828. * Checks if all the post processes in the effect are supported.
  66829. */
  66830. get: function () {
  66831. for (var index in this._postProcesses) {
  66832. for (var ppIndex in this._postProcesses[index]) {
  66833. if (!this._postProcesses[index][ppIndex].isSupported) {
  66834. return false;
  66835. }
  66836. }
  66837. }
  66838. return true;
  66839. },
  66840. enumerable: true,
  66841. configurable: true
  66842. });
  66843. /**
  66844. * Updates the current state of the effect
  66845. */
  66846. PostProcessRenderEffect.prototype._update = function () {
  66847. };
  66848. /**
  66849. * Attaches the effect on cameras
  66850. * @param cameras The camera to attach to.
  66851. */
  66852. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  66853. var _this = this;
  66854. var cameraKey;
  66855. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66856. if (!cams) {
  66857. return;
  66858. }
  66859. for (var i = 0; i < cams.length; i++) {
  66860. var camera = cams[i];
  66861. var cameraName = camera.name;
  66862. if (this._singleInstance) {
  66863. cameraKey = 0;
  66864. }
  66865. else {
  66866. cameraKey = cameraName;
  66867. }
  66868. if (!this._postProcesses[cameraKey]) {
  66869. var postProcess = this._getPostProcesses();
  66870. if (postProcess) {
  66871. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  66872. }
  66873. }
  66874. if (!this._indicesForCamera[cameraName]) {
  66875. this._indicesForCamera[cameraName] = [];
  66876. }
  66877. this._postProcesses[cameraKey].forEach(function (postProcess) {
  66878. var index = camera.attachPostProcess(postProcess);
  66879. _this._indicesForCamera[cameraName].push(index);
  66880. });
  66881. if (!this._cameras[cameraName]) {
  66882. this._cameras[cameraName] = camera;
  66883. }
  66884. }
  66885. };
  66886. /**
  66887. * Detatches the effect on cameras
  66888. * @param cameras The camera to detatch from.
  66889. */
  66890. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  66891. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66892. if (!cams) {
  66893. return;
  66894. }
  66895. for (var i = 0; i < cams.length; i++) {
  66896. var camera = cams[i];
  66897. var cameraName = camera.name;
  66898. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66899. camera.detachPostProcess(postProcess);
  66900. });
  66901. if (this._cameras[cameraName]) {
  66902. //this._indicesForCamera.splice(index, 1);
  66903. this._cameras[cameraName] = null;
  66904. }
  66905. }
  66906. };
  66907. /**
  66908. * Enables the effect on given cameras
  66909. * @param cameras The camera to enable.
  66910. */
  66911. PostProcessRenderEffect.prototype._enable = function (cameras) {
  66912. var _this = this;
  66913. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66914. if (!cams) {
  66915. return;
  66916. }
  66917. for (var i = 0; i < cams.length; i++) {
  66918. var camera = cams[i];
  66919. var cameraName = camera.name;
  66920. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  66921. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  66922. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66923. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  66924. });
  66925. }
  66926. }
  66927. }
  66928. };
  66929. /**
  66930. * Disables the effect on the given cameras
  66931. * @param cameras The camera to disable.
  66932. */
  66933. PostProcessRenderEffect.prototype._disable = function (cameras) {
  66934. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  66935. if (!cams) {
  66936. return;
  66937. }
  66938. for (var i = 0; i < cams.length; i++) {
  66939. var camera = cams[i];
  66940. var cameraName = camera.name;
  66941. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  66942. camera.detachPostProcess(postProcess);
  66943. });
  66944. }
  66945. };
  66946. /**
  66947. * Gets a list of the post processes contained in the effect.
  66948. * @param camera The camera to get the post processes on.
  66949. * @returns The list of the post processes in the effect.
  66950. */
  66951. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  66952. if (this._singleInstance) {
  66953. return this._postProcesses[0];
  66954. }
  66955. else {
  66956. if (!camera) {
  66957. return null;
  66958. }
  66959. return this._postProcesses[camera.name];
  66960. }
  66961. };
  66962. return PostProcessRenderEffect;
  66963. }());
  66964. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  66965. })(BABYLON || (BABYLON = {}));
  66966. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  66967. "use strict";
  66968. var BABYLON;
  66969. (function (BABYLON) {
  66970. var PostProcessRenderPipeline = /** @class */ (function () {
  66971. function PostProcessRenderPipeline(engine, name) {
  66972. this.engine = engine;
  66973. this._name = name;
  66974. this._renderEffects = {};
  66975. this._renderEffectsForIsolatedPass = new Array();
  66976. this._cameras = [];
  66977. }
  66978. PostProcessRenderPipeline.prototype.getClassName = function () {
  66979. return "PostProcessRenderPipeline";
  66980. };
  66981. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  66982. get: function () {
  66983. for (var renderEffectName in this._renderEffects) {
  66984. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  66985. if (!this._renderEffects[renderEffectName].isSupported) {
  66986. return false;
  66987. }
  66988. }
  66989. }
  66990. return true;
  66991. },
  66992. enumerable: true,
  66993. configurable: true
  66994. });
  66995. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  66996. this._renderEffects[renderEffect._name] = renderEffect;
  66997. };
  66998. // private
  66999. PostProcessRenderPipeline.prototype._rebuild = function () {
  67000. };
  67001. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  67002. var renderEffects = this._renderEffects[renderEffectName];
  67003. if (!renderEffects) {
  67004. return;
  67005. }
  67006. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67007. };
  67008. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  67009. var renderEffects = this._renderEffects[renderEffectName];
  67010. if (!renderEffects) {
  67011. return;
  67012. }
  67013. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67014. };
  67015. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  67016. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67017. if (!cams) {
  67018. return;
  67019. }
  67020. var indicesToDelete = [];
  67021. var i;
  67022. for (i = 0; i < cams.length; i++) {
  67023. var camera = cams[i];
  67024. var cameraName = camera.name;
  67025. if (this._cameras.indexOf(camera) === -1) {
  67026. this._cameras[cameraName] = camera;
  67027. }
  67028. else if (unique) {
  67029. indicesToDelete.push(i);
  67030. }
  67031. }
  67032. for (i = 0; i < indicesToDelete.length; i++) {
  67033. cameras.splice(indicesToDelete[i], 1);
  67034. }
  67035. for (var renderEffectName in this._renderEffects) {
  67036. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67037. this._renderEffects[renderEffectName]._attachCameras(cams);
  67038. }
  67039. }
  67040. };
  67041. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  67042. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67043. if (!cams) {
  67044. return;
  67045. }
  67046. for (var renderEffectName in this._renderEffects) {
  67047. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67048. this._renderEffects[renderEffectName]._detachCameras(cams);
  67049. }
  67050. }
  67051. for (var i = 0; i < cams.length; i++) {
  67052. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  67053. }
  67054. };
  67055. PostProcessRenderPipeline.prototype._update = function () {
  67056. for (var renderEffectName in this._renderEffects) {
  67057. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67058. this._renderEffects[renderEffectName]._update();
  67059. }
  67060. }
  67061. for (var i = 0; i < this._cameras.length; i++) {
  67062. var cameraName = this._cameras[i].name;
  67063. if (this._renderEffectsForIsolatedPass[cameraName]) {
  67064. this._renderEffectsForIsolatedPass[cameraName]._update();
  67065. }
  67066. }
  67067. };
  67068. PostProcessRenderPipeline.prototype._reset = function () {
  67069. this._renderEffects = {};
  67070. this._renderEffectsForIsolatedPass = new Array();
  67071. };
  67072. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  67073. // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
  67074. var effectKeys = Object.keys(this._renderEffects);
  67075. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  67076. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  67077. if (postProcesses) {
  67078. postProcesses[0].samples = 4;
  67079. return true;
  67080. }
  67081. }
  67082. return false;
  67083. };
  67084. PostProcessRenderPipeline.prototype.dispose = function () {
  67085. // Must be implemented by children
  67086. };
  67087. __decorate([
  67088. BABYLON.serialize()
  67089. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  67090. return PostProcessRenderPipeline;
  67091. }());
  67092. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  67093. })(BABYLON || (BABYLON = {}));
  67094. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  67095. "use strict";
  67096. var BABYLON;
  67097. (function (BABYLON) {
  67098. /**
  67099. * This represents a depth renderer in Babylon.
  67100. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  67101. */
  67102. var DepthRenderer = /** @class */ (function () {
  67103. /**
  67104. * Instantiates a depth renderer
  67105. * @param scene The scene the renderer belongs to
  67106. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  67107. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  67108. */
  67109. function DepthRenderer(scene, type, camera) {
  67110. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67111. if (camera === void 0) { camera = null; }
  67112. var _this = this;
  67113. this._scene = scene;
  67114. this._camera = camera;
  67115. var engine = scene.getEngine();
  67116. // Render target
  67117. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  67118. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67119. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67120. this._depthMap.refreshRate = 1;
  67121. this._depthMap.renderParticles = false;
  67122. this._depthMap.renderList = null;
  67123. // Camera to get depth map from to support multiple concurrent cameras
  67124. this._depthMap.activeCamera = this._camera;
  67125. this._depthMap.ignoreCameraViewport = true;
  67126. this._depthMap.useCameraPostProcesses = false;
  67127. // set default depth value to 1.0 (far away)
  67128. this._depthMap.onClearObservable.add(function (engine) {
  67129. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  67130. });
  67131. // Custom render function
  67132. var renderSubMesh = function (subMesh) {
  67133. var mesh = subMesh.getRenderingMesh();
  67134. var scene = _this._scene;
  67135. var engine = scene.getEngine();
  67136. var material = subMesh.getMaterial();
  67137. if (!material) {
  67138. return;
  67139. }
  67140. // Culling and reverse (right handed system)
  67141. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67142. // Managing instances
  67143. var batch = mesh._getInstancesRenderList(subMesh._id);
  67144. if (batch.mustReturn) {
  67145. return;
  67146. }
  67147. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67148. var camera = _this._camera || scene.activeCamera;
  67149. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  67150. engine.enableEffect(_this._effect);
  67151. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67152. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67153. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  67154. // Alpha test
  67155. if (material && material.needAlphaTesting()) {
  67156. var alphaTexture = material.getAlphaTestTexture();
  67157. if (alphaTexture) {
  67158. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67159. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67160. }
  67161. }
  67162. // Bones
  67163. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67164. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67165. }
  67166. // Draw
  67167. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67168. }
  67169. };
  67170. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67171. var index;
  67172. if (depthOnlySubMeshes.length) {
  67173. engine.setColorWrite(false);
  67174. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67175. renderSubMesh(depthOnlySubMeshes.data[index]);
  67176. }
  67177. engine.setColorWrite(true);
  67178. }
  67179. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67180. renderSubMesh(opaqueSubMeshes.data[index]);
  67181. }
  67182. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67183. renderSubMesh(alphaTestSubMeshes.data[index]);
  67184. }
  67185. };
  67186. }
  67187. /**
  67188. * Creates the depth rendering effect and checks if the effect is ready.
  67189. * @param subMesh The submesh to be used to render the depth map of
  67190. * @param useInstances If multiple world instances should be used
  67191. * @returns if the depth renderer is ready to render the depth map
  67192. */
  67193. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  67194. var material = subMesh.getMaterial();
  67195. if (material.disableDepthWrite) {
  67196. return false;
  67197. }
  67198. var defines = [];
  67199. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67200. var mesh = subMesh.getMesh();
  67201. // Alpha test
  67202. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  67203. defines.push("#define ALPHATEST");
  67204. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67205. attribs.push(BABYLON.VertexBuffer.UVKind);
  67206. defines.push("#define UV1");
  67207. }
  67208. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67209. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67210. defines.push("#define UV2");
  67211. }
  67212. }
  67213. // Bones
  67214. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67215. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67216. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67217. if (mesh.numBoneInfluencers > 4) {
  67218. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67219. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67220. }
  67221. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67222. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67223. }
  67224. else {
  67225. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67226. }
  67227. // Instances
  67228. if (useInstances) {
  67229. defines.push("#define INSTANCES");
  67230. attribs.push("world0");
  67231. attribs.push("world1");
  67232. attribs.push("world2");
  67233. attribs.push("world3");
  67234. }
  67235. // Get correct effect
  67236. var join = defines.join("\n");
  67237. if (this._cachedDefines !== join) {
  67238. this._cachedDefines = join;
  67239. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  67240. }
  67241. return this._effect.isReady();
  67242. };
  67243. /**
  67244. * Gets the texture which the depth map will be written to.
  67245. * @returns The depth map texture
  67246. */
  67247. DepthRenderer.prototype.getDepthMap = function () {
  67248. return this._depthMap;
  67249. };
  67250. /**
  67251. * Disposes of the depth renderer.
  67252. */
  67253. DepthRenderer.prototype.dispose = function () {
  67254. this._depthMap.dispose();
  67255. };
  67256. return DepthRenderer;
  67257. }());
  67258. BABYLON.DepthRenderer = DepthRenderer;
  67259. })(BABYLON || (BABYLON = {}));
  67260. //# sourceMappingURL=babylon.depthRenderer.js.map
  67261. "use strict";
  67262. var BABYLON;
  67263. (function (BABYLON) {
  67264. var SSAORenderingPipeline = /** @class */ (function (_super) {
  67265. __extends(SSAORenderingPipeline, _super);
  67266. /**
  67267. * @constructor
  67268. * @param {string} name - The rendering pipeline name
  67269. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67270. * @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 }
  67271. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67272. */
  67273. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  67274. var _this = _super.call(this, scene.getEngine(), name) || this;
  67275. // Members
  67276. /**
  67277. * The PassPostProcess id in the pipeline that contains the original scene color
  67278. * @type {string}
  67279. */
  67280. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67281. /**
  67282. * The SSAO PostProcess id in the pipeline
  67283. * @type {string}
  67284. */
  67285. _this.SSAORenderEffect = "SSAORenderEffect";
  67286. /**
  67287. * The horizontal blur PostProcess id in the pipeline
  67288. * @type {string}
  67289. */
  67290. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67291. /**
  67292. * The vertical blur PostProcess id in the pipeline
  67293. * @type {string}
  67294. */
  67295. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67296. /**
  67297. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67298. * @type {string}
  67299. */
  67300. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67301. /**
  67302. * The output strength of the SSAO post-process. Default value is 1.0.
  67303. * @type {number}
  67304. */
  67305. _this.totalStrength = 1.0;
  67306. /**
  67307. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  67308. * @type {number}
  67309. */
  67310. _this.radius = 0.0001;
  67311. /**
  67312. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  67313. * Must not be equal to fallOff and superior to fallOff.
  67314. * Default value is 0.975
  67315. * @type {number}
  67316. */
  67317. _this.area = 0.0075;
  67318. /**
  67319. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  67320. * Must not be equal to area and inferior to area.
  67321. * Default value is 0.0
  67322. * @type {number}
  67323. */
  67324. _this.fallOff = 0.000001;
  67325. /**
  67326. * The base color of the SSAO post-process
  67327. * The final result is "base + ssao" between [0, 1]
  67328. * @type {number}
  67329. */
  67330. _this.base = 0.5;
  67331. _this._firstUpdate = true;
  67332. _this._scene = scene;
  67333. // Set up assets
  67334. _this._createRandomTexture();
  67335. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67336. var ssaoRatio = ratio.ssaoRatio || ratio;
  67337. var combineRatio = ratio.combineRatio || ratio;
  67338. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67339. _this._createSSAOPostProcess(ssaoRatio);
  67340. _this._createBlurPostProcess(ssaoRatio);
  67341. _this._createSSAOCombinePostProcess(combineRatio);
  67342. // Set up pipeline
  67343. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67344. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67345. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67346. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67347. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67348. // Finish
  67349. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67350. if (cameras)
  67351. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67352. return _this;
  67353. }
  67354. // Public Methods
  67355. /**
  67356. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67357. */
  67358. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67359. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67360. for (var i = 0; i < this._scene.cameras.length; i++) {
  67361. var camera = this._scene.cameras[i];
  67362. this._originalColorPostProcess.dispose(camera);
  67363. this._ssaoPostProcess.dispose(camera);
  67364. this._blurHPostProcess.dispose(camera);
  67365. this._blurVPostProcess.dispose(camera);
  67366. this._ssaoCombinePostProcess.dispose(camera);
  67367. }
  67368. this._randomTexture.dispose();
  67369. if (disableDepthRender)
  67370. this._scene.disableDepthRenderer();
  67371. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67372. _super.prototype.dispose.call(this);
  67373. };
  67374. // Private Methods
  67375. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  67376. var _this = this;
  67377. var size = 16;
  67378. 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);
  67379. 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);
  67380. this._blurHPostProcess.onActivateObservable.add(function () {
  67381. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  67382. _this._blurHPostProcess.kernel = size * dw;
  67383. });
  67384. this._blurVPostProcess.onActivateObservable.add(function () {
  67385. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  67386. _this._blurVPostProcess.kernel = size * dw;
  67387. });
  67388. };
  67389. SSAORenderingPipeline.prototype._rebuild = function () {
  67390. this._firstUpdate = true;
  67391. _super.prototype._rebuild.call(this);
  67392. };
  67393. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67394. var _this = this;
  67395. var numSamples = 16;
  67396. var sampleSphere = [
  67397. 0.5381, 0.1856, -0.4319,
  67398. 0.1379, 0.2486, 0.4430,
  67399. 0.3371, 0.5679, -0.0057,
  67400. -0.6999, -0.0451, -0.0019,
  67401. 0.0689, -0.1598, -0.8547,
  67402. 0.0560, 0.0069, -0.1843,
  67403. -0.0146, 0.1402, 0.0762,
  67404. 0.0100, -0.1924, -0.0344,
  67405. -0.3577, -0.5301, -0.4358,
  67406. -0.3169, 0.1063, 0.0158,
  67407. 0.0103, -0.5869, 0.0046,
  67408. -0.0897, -0.4940, 0.3287,
  67409. 0.7119, -0.0154, -0.0918,
  67410. -0.0533, 0.0596, -0.5411,
  67411. 0.0352, -0.0631, 0.5460,
  67412. -0.4776, 0.2847, -0.0271
  67413. ];
  67414. var samplesFactor = 1.0 / numSamples;
  67415. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  67416. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67417. "area", "fallOff", "base", "range", "viewport"
  67418. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67419. this._ssaoPostProcess.onApply = function (effect) {
  67420. if (_this._firstUpdate) {
  67421. effect.setArray3("sampleSphere", sampleSphere);
  67422. effect.setFloat("samplesFactor", samplesFactor);
  67423. effect.setFloat("randTextureTiles", 4.0);
  67424. }
  67425. effect.setFloat("totalStrength", _this.totalStrength);
  67426. effect.setFloat("radius", _this.radius);
  67427. effect.setFloat("area", _this.area);
  67428. effect.setFloat("fallOff", _this.fallOff);
  67429. effect.setFloat("base", _this.base);
  67430. effect.setTexture("textureSampler", _this._depthTexture);
  67431. effect.setTexture("randomSampler", _this._randomTexture);
  67432. };
  67433. };
  67434. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67435. var _this = this;
  67436. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67437. this._ssaoCombinePostProcess.onApply = function (effect) {
  67438. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67439. };
  67440. };
  67441. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  67442. var size = 512;
  67443. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67444. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67445. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67446. var context = this._randomTexture.getContext();
  67447. var rand = function (min, max) {
  67448. return Math.random() * (max - min) + min;
  67449. };
  67450. var randVector = BABYLON.Vector3.Zero();
  67451. for (var x = 0; x < size; x++) {
  67452. for (var y = 0; y < size; y++) {
  67453. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  67454. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  67455. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  67456. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67457. context.fillRect(x, y, 1, 1);
  67458. }
  67459. }
  67460. this._randomTexture.update(false);
  67461. };
  67462. __decorate([
  67463. BABYLON.serialize()
  67464. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  67465. __decorate([
  67466. BABYLON.serialize()
  67467. ], SSAORenderingPipeline.prototype, "radius", void 0);
  67468. __decorate([
  67469. BABYLON.serialize()
  67470. ], SSAORenderingPipeline.prototype, "area", void 0);
  67471. __decorate([
  67472. BABYLON.serialize()
  67473. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  67474. __decorate([
  67475. BABYLON.serialize()
  67476. ], SSAORenderingPipeline.prototype, "base", void 0);
  67477. return SSAORenderingPipeline;
  67478. }(BABYLON.PostProcessRenderPipeline));
  67479. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  67480. })(BABYLON || (BABYLON = {}));
  67481. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  67482. "use strict";
  67483. var BABYLON;
  67484. (function (BABYLON) {
  67485. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  67486. __extends(SSAO2RenderingPipeline, _super);
  67487. /**
  67488. * @constructor
  67489. * @param {string} name - The rendering pipeline name
  67490. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67491. * @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 }
  67492. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67493. */
  67494. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  67495. var _this = _super.call(this, scene.getEngine(), name) || this;
  67496. // Members
  67497. /**
  67498. * The PassPostProcess id in the pipeline that contains the original scene color
  67499. * @type {string}
  67500. */
  67501. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67502. /**
  67503. * The SSAO PostProcess id in the pipeline
  67504. * @type {string}
  67505. */
  67506. _this.SSAORenderEffect = "SSAORenderEffect";
  67507. /**
  67508. * The horizontal blur PostProcess id in the pipeline
  67509. * @type {string}
  67510. */
  67511. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67512. /**
  67513. * The vertical blur PostProcess id in the pipeline
  67514. * @type {string}
  67515. */
  67516. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67517. /**
  67518. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67519. * @type {string}
  67520. */
  67521. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  67522. /**
  67523. * The output strength of the SSAO post-process. Default value is 1.0.
  67524. * @type {number}
  67525. */
  67526. _this.totalStrength = 1.0;
  67527. /**
  67528. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  67529. * @type {number}
  67530. */
  67531. _this.maxZ = 100.0;
  67532. /**
  67533. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  67534. * @type {number}
  67535. */
  67536. _this.minZAspect = 0.2;
  67537. /**
  67538. * Number of samples used for the SSAO calculations. Default value is 8
  67539. * @type {number}
  67540. */
  67541. _this._samples = 8;
  67542. /**
  67543. * Are we using bilateral blur ?
  67544. * @type {boolean}
  67545. */
  67546. _this._expensiveBlur = true;
  67547. /**
  67548. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  67549. * @type {number}
  67550. */
  67551. _this.radius = 2.0;
  67552. /**
  67553. * The base color of the SSAO post-process
  67554. * The final result is "base + ssao" between [0, 1]
  67555. * @type {number}
  67556. */
  67557. _this.base = 0.1;
  67558. _this._firstUpdate = true;
  67559. _this._scene = scene;
  67560. if (!_this.isSupported) {
  67561. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  67562. return _this;
  67563. }
  67564. var ssaoRatio = ratio.ssaoRatio || ratio;
  67565. var blurRatio = ratio.blurRatio || ratio;
  67566. // Set up assets
  67567. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  67568. _this._createRandomTexture();
  67569. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  67570. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  67571. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  67572. _this._createSSAOPostProcess(1.0);
  67573. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  67574. _this._createSSAOCombinePostProcess(blurRatio);
  67575. // Set up pipeline
  67576. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  67577. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  67578. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  67579. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  67580. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  67581. // Finish
  67582. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67583. if (cameras)
  67584. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67585. return _this;
  67586. }
  67587. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  67588. get: function () {
  67589. return this._samples;
  67590. },
  67591. set: function (n) {
  67592. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  67593. this._samples = n;
  67594. this._sampleSphere = this._generateHemisphere();
  67595. this._firstUpdate = true;
  67596. },
  67597. enumerable: true,
  67598. configurable: true
  67599. });
  67600. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  67601. get: function () {
  67602. return this._expensiveBlur;
  67603. },
  67604. set: function (b) {
  67605. 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"]);
  67606. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  67607. this._expensiveBlur = b;
  67608. this._firstUpdate = true;
  67609. },
  67610. enumerable: true,
  67611. configurable: true
  67612. });
  67613. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  67614. /**
  67615. * Support test.
  67616. * @type {boolean}
  67617. */
  67618. get: function () {
  67619. var engine = BABYLON.Engine.LastCreatedEngine;
  67620. if (!engine) {
  67621. return false;
  67622. }
  67623. return engine.getCaps().drawBuffersExtension;
  67624. },
  67625. enumerable: true,
  67626. configurable: true
  67627. });
  67628. // Public Methods
  67629. /**
  67630. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  67631. */
  67632. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  67633. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  67634. for (var i = 0; i < this._scene.cameras.length; i++) {
  67635. var camera = this._scene.cameras[i];
  67636. this._originalColorPostProcess.dispose(camera);
  67637. this._ssaoPostProcess.dispose(camera);
  67638. this._blurHPostProcess.dispose(camera);
  67639. this._blurVPostProcess.dispose(camera);
  67640. this._ssaoCombinePostProcess.dispose(camera);
  67641. }
  67642. this._randomTexture.dispose();
  67643. if (disableGeometryBufferRenderer)
  67644. this._scene.disableGeometryBufferRenderer();
  67645. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67646. _super.prototype.dispose.call(this);
  67647. };
  67648. // Private Methods
  67649. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  67650. var _this = this;
  67651. this._samplerOffsets = [];
  67652. var expensive = this.expensiveBlur;
  67653. for (var i = -8; i < 8; i++) {
  67654. this._samplerOffsets.push(i * 2 + 0.5);
  67655. }
  67656. 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");
  67657. this._blurHPostProcess.onApply = function (effect) {
  67658. if (!_this._scene.activeCamera) {
  67659. return;
  67660. }
  67661. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  67662. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67663. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67664. effect.setFloat("radius", _this.radius);
  67665. effect.setTexture("depthSampler", _this._depthTexture);
  67666. if (_this._firstUpdate) {
  67667. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67668. }
  67669. };
  67670. 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");
  67671. this._blurVPostProcess.onApply = function (effect) {
  67672. if (!_this._scene.activeCamera) {
  67673. return;
  67674. }
  67675. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  67676. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67677. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67678. effect.setFloat("radius", _this.radius);
  67679. effect.setTexture("depthSampler", _this._depthTexture);
  67680. if (_this._firstUpdate) {
  67681. effect.setArray("samplerOffsets", _this._samplerOffsets);
  67682. _this._firstUpdate = false;
  67683. }
  67684. };
  67685. };
  67686. SSAO2RenderingPipeline.prototype._rebuild = function () {
  67687. this._firstUpdate = true;
  67688. _super.prototype._rebuild.call(this);
  67689. };
  67690. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  67691. var numSamples = this.samples;
  67692. var result = [];
  67693. var vector, scale;
  67694. var rand = function (min, max) {
  67695. return Math.random() * (max - min) + min;
  67696. };
  67697. var i = 0;
  67698. while (i < numSamples) {
  67699. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  67700. vector.normalize();
  67701. scale = i / numSamples;
  67702. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  67703. vector.scaleInPlace(scale);
  67704. result.push(vector.x, vector.y, vector.z);
  67705. i++;
  67706. }
  67707. return result;
  67708. };
  67709. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  67710. var _this = this;
  67711. var numSamples = this.samples;
  67712. this._sampleSphere = this._generateHemisphere();
  67713. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  67714. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  67715. "base", "range", "projection", "near", "far", "texelSize",
  67716. "xViewport", "yViewport", "maxZ", "minZAspect"
  67717. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  67718. this._ssaoPostProcess.onApply = function (effect) {
  67719. if (_this._firstUpdate) {
  67720. effect.setArray3("sampleSphere", _this._sampleSphere);
  67721. effect.setFloat("randTextureTiles", 4.0);
  67722. }
  67723. if (!_this._scene.activeCamera) {
  67724. return;
  67725. }
  67726. effect.setFloat("samplesFactor", 1 / _this.samples);
  67727. effect.setFloat("totalStrength", _this.totalStrength);
  67728. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  67729. effect.setFloat("radius", _this.radius);
  67730. effect.setFloat("maxZ", _this.maxZ);
  67731. effect.setFloat("minZAspect", _this.minZAspect);
  67732. effect.setFloat("base", _this.base);
  67733. effect.setFloat("near", _this._scene.activeCamera.minZ);
  67734. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  67735. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  67736. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  67737. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  67738. effect.setTexture("textureSampler", _this._depthTexture);
  67739. effect.setTexture("normalSampler", _this._normalTexture);
  67740. effect.setTexture("randomSampler", _this._randomTexture);
  67741. };
  67742. };
  67743. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  67744. var _this = this;
  67745. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67746. this._ssaoCombinePostProcess.onApply = function (effect) {
  67747. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  67748. };
  67749. };
  67750. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  67751. var size = 512;
  67752. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67753. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67754. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67755. var context = this._randomTexture.getContext();
  67756. var rand = function (min, max) {
  67757. return Math.random() * (max - min) + min;
  67758. };
  67759. var randVector = BABYLON.Vector3.Zero();
  67760. for (var x = 0; x < size; x++) {
  67761. for (var y = 0; y < size; y++) {
  67762. randVector.x = rand(0.0, 1.0);
  67763. randVector.y = rand(0.0, 1.0);
  67764. randVector.z = 0.0;
  67765. randVector.normalize();
  67766. randVector.scaleInPlace(255);
  67767. randVector.x = Math.floor(randVector.x);
  67768. randVector.y = Math.floor(randVector.y);
  67769. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  67770. context.fillRect(x, y, 1, 1);
  67771. }
  67772. }
  67773. this._randomTexture.update(false);
  67774. };
  67775. __decorate([
  67776. BABYLON.serialize()
  67777. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  67778. __decorate([
  67779. BABYLON.serialize()
  67780. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  67781. __decorate([
  67782. BABYLON.serialize()
  67783. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  67784. __decorate([
  67785. BABYLON.serialize("samples")
  67786. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  67787. __decorate([
  67788. BABYLON.serialize("expensiveBlur")
  67789. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  67790. __decorate([
  67791. BABYLON.serialize()
  67792. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  67793. __decorate([
  67794. BABYLON.serialize()
  67795. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  67796. return SSAO2RenderingPipeline;
  67797. }(BABYLON.PostProcessRenderPipeline));
  67798. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  67799. })(BABYLON || (BABYLON = {}));
  67800. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  67801. "use strict";
  67802. // BABYLON.JS Chromatic Aberration GLSL Shader
  67803. // Author: Olivier Guyot
  67804. // Separates very slightly R, G and B colors on the edges of the screen
  67805. // Inspired by Francois Tarlier & Martins Upitis
  67806. var BABYLON;
  67807. (function (BABYLON) {
  67808. var LensRenderingPipeline = /** @class */ (function (_super) {
  67809. __extends(LensRenderingPipeline, _super);
  67810. /**
  67811. * @constructor
  67812. *
  67813. * Effect parameters are as follow:
  67814. * {
  67815. * chromatic_aberration: number; // from 0 to x (1 for realism)
  67816. * edge_blur: number; // from 0 to x (1 for realism)
  67817. * distortion: number; // from 0 to x (1 for realism)
  67818. * grain_amount: number; // from 0 to 1
  67819. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  67820. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  67821. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  67822. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  67823. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  67824. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  67825. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  67826. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  67827. * }
  67828. * Note: if an effect parameter is unset, effect is disabled
  67829. *
  67830. * @param {string} name - The rendering pipeline name
  67831. * @param {object} parameters - An object containing all parameters (see above)
  67832. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67833. * @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)
  67834. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67835. */
  67836. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  67837. if (ratio === void 0) { ratio = 1.0; }
  67838. var _this = _super.call(this, scene.getEngine(), name) || this;
  67839. // Lens effects can be of the following:
  67840. // - chromatic aberration (slight shift of RGB colors)
  67841. // - blur on the edge of the lens
  67842. // - lens distortion
  67843. // - depth-of-field blur & highlights enhancing
  67844. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  67845. // - grain effect (noise or custom texture)
  67846. // Two additional texture samplers are needed:
  67847. // - depth map (for depth-of-field)
  67848. // - grain texture
  67849. /**
  67850. * The chromatic aberration PostProcess id in the pipeline
  67851. * @type {string}
  67852. */
  67853. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  67854. /**
  67855. * The highlights enhancing PostProcess id in the pipeline
  67856. * @type {string}
  67857. */
  67858. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  67859. /**
  67860. * The depth-of-field PostProcess id in the pipeline
  67861. * @type {string}
  67862. */
  67863. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  67864. _this._scene = scene;
  67865. // Fetch texture samplers
  67866. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  67867. if (parameters.grain_texture) {
  67868. _this._grainTexture = parameters.grain_texture;
  67869. }
  67870. else {
  67871. _this._createGrainTexture();
  67872. }
  67873. // save parameters
  67874. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  67875. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  67876. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  67877. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  67878. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  67879. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  67880. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  67881. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  67882. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  67883. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  67884. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  67885. // Create effects
  67886. _this._createChromaticAberrationPostProcess(ratio);
  67887. _this._createHighlightsPostProcess(ratio);
  67888. _this._createDepthOfFieldPostProcess(ratio / 4);
  67889. // Set up pipeline
  67890. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  67891. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  67892. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  67893. if (_this._highlightsGain === -1) {
  67894. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  67895. }
  67896. // Finish
  67897. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67898. if (cameras) {
  67899. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  67900. }
  67901. return _this;
  67902. }
  67903. // public methods (self explanatory)
  67904. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  67905. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  67906. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  67907. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  67908. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  67909. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  67910. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  67911. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  67912. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  67913. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  67914. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  67915. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  67916. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  67917. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  67918. };
  67919. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  67920. this._highlightsPostProcess.updateEffect();
  67921. };
  67922. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  67923. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  67924. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  67925. this._highlightsGain = amount;
  67926. };
  67927. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  67928. if (this._highlightsGain === -1) {
  67929. this._highlightsGain = 1.0;
  67930. }
  67931. this._highlightsThreshold = amount;
  67932. };
  67933. LensRenderingPipeline.prototype.disableHighlights = function () {
  67934. this._highlightsGain = -1;
  67935. };
  67936. /**
  67937. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  67938. */
  67939. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  67940. if (disableDepthRender === void 0) { disableDepthRender = false; }
  67941. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  67942. this._chromaticAberrationPostProcess = null;
  67943. this._highlightsPostProcess = null;
  67944. this._depthOfFieldPostProcess = null;
  67945. this._grainTexture.dispose();
  67946. if (disableDepthRender)
  67947. this._scene.disableDepthRenderer();
  67948. };
  67949. // colors shifting and distortion
  67950. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  67951. var _this = this;
  67952. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  67953. [], // samplers
  67954. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67955. this._chromaticAberrationPostProcess.onApply = function (effect) {
  67956. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  67957. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67958. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67959. effect.setFloat('radialIntensity', 1);
  67960. effect.setFloat2('direction', 17, 17);
  67961. effect.setFloat2('centerPosition', 0.5, 0.5);
  67962. };
  67963. };
  67964. // highlights enhancing
  67965. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  67966. var _this = this;
  67967. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  67968. [], // samplers
  67969. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  67970. this._highlightsPostProcess.onApply = function (effect) {
  67971. effect.setFloat('gain', _this._highlightsGain);
  67972. effect.setFloat('threshold', _this._highlightsThreshold);
  67973. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  67974. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67975. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67976. };
  67977. };
  67978. // colors shifting and distortion
  67979. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  67980. var _this = this;
  67981. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  67982. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  67983. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  67984. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  67985. this._depthOfFieldPostProcess.onApply = function (effect) {
  67986. effect.setTexture("depthSampler", _this._depthTexture);
  67987. effect.setTexture("grainSampler", _this._grainTexture);
  67988. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  67989. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  67990. effect.setFloat('grain_amount', _this._grainAmount);
  67991. effect.setBool('blur_noise', _this._blurNoise);
  67992. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  67993. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  67994. effect.setFloat('distortion', _this._distortion);
  67995. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  67996. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  67997. effect.setFloat('aperture', _this._dofAperture);
  67998. effect.setFloat('darken', _this._dofDarken);
  67999. effect.setFloat('edge_blur', _this._edgeBlur);
  68000. effect.setBool('highlights', (_this._highlightsGain !== -1));
  68001. if (_this._scene.activeCamera) {
  68002. effect.setFloat('near', _this._scene.activeCamera.minZ);
  68003. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  68004. }
  68005. };
  68006. };
  68007. // creates a black and white random noise texture, 512x512
  68008. LensRenderingPipeline.prototype._createGrainTexture = function () {
  68009. var size = 512;
  68010. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68011. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68012. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68013. var context = this._grainTexture.getContext();
  68014. var rand = function (min, max) {
  68015. return Math.random() * (max - min) + min;
  68016. };
  68017. var value;
  68018. for (var x = 0; x < size; x++) {
  68019. for (var y = 0; y < size; y++) {
  68020. value = Math.floor(rand(0.42, 0.58) * 255);
  68021. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  68022. context.fillRect(x, y, 1, 1);
  68023. }
  68024. }
  68025. this._grainTexture.update(false);
  68026. };
  68027. return LensRenderingPipeline;
  68028. }(BABYLON.PostProcessRenderPipeline));
  68029. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  68030. })(BABYLON || (BABYLON = {}));
  68031. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  68032. "use strict";
  68033. var BABYLON;
  68034. (function (BABYLON) {
  68035. var StandardRenderingPipeline = /** @class */ (function (_super) {
  68036. __extends(StandardRenderingPipeline, _super);
  68037. /**
  68038. * @constructor
  68039. * @param {string} name - The rendering pipeline name
  68040. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68041. * @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)
  68042. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  68043. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68044. */
  68045. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  68046. if (originalPostProcess === void 0) { originalPostProcess = null; }
  68047. var _this = _super.call(this, scene.getEngine(), name) || this;
  68048. _this.downSampleX4PostProcess = null;
  68049. _this.brightPassPostProcess = null;
  68050. _this.blurHPostProcesses = [];
  68051. _this.blurVPostProcesses = [];
  68052. _this.textureAdderPostProcess = null;
  68053. _this.volumetricLightPostProcess = null;
  68054. _this.volumetricLightSmoothXPostProcess = null;
  68055. _this.volumetricLightSmoothYPostProcess = null;
  68056. _this.volumetricLightMergePostProces = null;
  68057. _this.volumetricLightFinalPostProcess = null;
  68058. _this.luminancePostProcess = null;
  68059. _this.luminanceDownSamplePostProcesses = [];
  68060. _this.hdrPostProcess = null;
  68061. _this.textureAdderFinalPostProcess = null;
  68062. _this.lensFlareFinalPostProcess = null;
  68063. _this.hdrFinalPostProcess = null;
  68064. _this.lensFlarePostProcess = null;
  68065. _this.lensFlareComposePostProcess = null;
  68066. _this.motionBlurPostProcess = null;
  68067. _this.depthOfFieldPostProcess = null;
  68068. // Values
  68069. _this.brightThreshold = 1.0;
  68070. _this.blurWidth = 512.0;
  68071. _this.horizontalBlur = false;
  68072. _this.exposure = 1.0;
  68073. _this.lensTexture = null;
  68074. _this.volumetricLightCoefficient = 0.2;
  68075. _this.volumetricLightPower = 4.0;
  68076. _this.volumetricLightBlurScale = 64.0;
  68077. _this.sourceLight = null;
  68078. _this.hdrMinimumLuminance = 1.0;
  68079. _this.hdrDecreaseRate = 0.5;
  68080. _this.hdrIncreaseRate = 0.5;
  68081. _this.lensColorTexture = null;
  68082. _this.lensFlareStrength = 20.0;
  68083. _this.lensFlareGhostDispersal = 1.4;
  68084. _this.lensFlareHaloWidth = 0.7;
  68085. _this.lensFlareDistortionStrength = 16.0;
  68086. _this.lensStarTexture = null;
  68087. _this.lensFlareDirtTexture = null;
  68088. _this.depthOfFieldDistance = 10.0;
  68089. _this.depthOfFieldBlurWidth = 64.0;
  68090. _this.motionStrength = 1.0;
  68091. // IAnimatable
  68092. _this.animations = [];
  68093. _this._currentDepthOfFieldSource = null;
  68094. _this._hdrCurrentLuminance = 1.0;
  68095. // Getters and setters
  68096. _this._bloomEnabled = true;
  68097. _this._depthOfFieldEnabled = false;
  68098. _this._vlsEnabled = false;
  68099. _this._lensFlareEnabled = false;
  68100. _this._hdrEnabled = false;
  68101. _this._motionBlurEnabled = false;
  68102. _this._motionBlurSamples = 64.0;
  68103. _this._volumetricLightStepsCount = 50.0;
  68104. _this._cameras = cameras || [];
  68105. // Initialize
  68106. _this._scene = scene;
  68107. _this._basePostProcess = originalPostProcess;
  68108. _this._ratio = ratio;
  68109. // Misc
  68110. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68111. // Finish
  68112. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68113. _this._buildPipeline();
  68114. return _this;
  68115. }
  68116. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  68117. get: function () {
  68118. return this._bloomEnabled;
  68119. },
  68120. set: function (enabled) {
  68121. if (this._bloomEnabled === enabled) {
  68122. return;
  68123. }
  68124. this._bloomEnabled = enabled;
  68125. this._buildPipeline();
  68126. },
  68127. enumerable: true,
  68128. configurable: true
  68129. });
  68130. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  68131. get: function () {
  68132. return this._depthOfFieldEnabled;
  68133. },
  68134. set: function (enabled) {
  68135. if (this._depthOfFieldEnabled === enabled) {
  68136. return;
  68137. }
  68138. this._depthOfFieldEnabled = enabled;
  68139. this._buildPipeline();
  68140. },
  68141. enumerable: true,
  68142. configurable: true
  68143. });
  68144. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  68145. get: function () {
  68146. return this._lensFlareEnabled;
  68147. },
  68148. set: function (enabled) {
  68149. if (this._lensFlareEnabled === enabled) {
  68150. return;
  68151. }
  68152. this._lensFlareEnabled = enabled;
  68153. this._buildPipeline();
  68154. },
  68155. enumerable: true,
  68156. configurable: true
  68157. });
  68158. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  68159. get: function () {
  68160. return this._hdrEnabled;
  68161. },
  68162. set: function (enabled) {
  68163. if (this._hdrEnabled === enabled) {
  68164. return;
  68165. }
  68166. this._hdrEnabled = enabled;
  68167. this._buildPipeline();
  68168. },
  68169. enumerable: true,
  68170. configurable: true
  68171. });
  68172. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  68173. get: function () {
  68174. return this._vlsEnabled;
  68175. },
  68176. set: function (enabled) {
  68177. if (this._vlsEnabled === enabled) {
  68178. return;
  68179. }
  68180. if (enabled) {
  68181. var geometry = this._scene.enableGeometryBufferRenderer();
  68182. if (!geometry) {
  68183. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  68184. return;
  68185. }
  68186. }
  68187. this._vlsEnabled = enabled;
  68188. this._buildPipeline();
  68189. },
  68190. enumerable: true,
  68191. configurable: true
  68192. });
  68193. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  68194. get: function () {
  68195. return this._motionBlurEnabled;
  68196. },
  68197. set: function (enabled) {
  68198. if (this._motionBlurEnabled === enabled) {
  68199. return;
  68200. }
  68201. this._motionBlurEnabled = enabled;
  68202. this._buildPipeline();
  68203. },
  68204. enumerable: true,
  68205. configurable: true
  68206. });
  68207. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  68208. get: function () {
  68209. return this._volumetricLightStepsCount;
  68210. },
  68211. set: function (count) {
  68212. if (this.volumetricLightPostProcess) {
  68213. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  68214. }
  68215. this._volumetricLightStepsCount = count;
  68216. },
  68217. enumerable: true,
  68218. configurable: true
  68219. });
  68220. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  68221. get: function () {
  68222. return this._motionBlurSamples;
  68223. },
  68224. set: function (samples) {
  68225. if (this.motionBlurPostProcess) {
  68226. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  68227. }
  68228. this._motionBlurSamples = samples;
  68229. },
  68230. enumerable: true,
  68231. configurable: true
  68232. });
  68233. StandardRenderingPipeline.prototype._buildPipeline = function () {
  68234. var _this = this;
  68235. var ratio = this._ratio;
  68236. var scene = this._scene;
  68237. this._disposePostProcesses();
  68238. this._reset();
  68239. // Create pass post-process
  68240. if (!this._basePostProcess) {
  68241. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  68242. this.originalPostProcess.onApply = function (effect) {
  68243. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  68244. };
  68245. }
  68246. else {
  68247. this.originalPostProcess = this._basePostProcess;
  68248. }
  68249. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  68250. this._currentDepthOfFieldSource = this.originalPostProcess;
  68251. if (this._vlsEnabled) {
  68252. // Create volumetric light
  68253. this._createVolumetricLightPostProcess(scene, ratio);
  68254. // Create volumetric light final post-process
  68255. 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);
  68256. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  68257. }
  68258. if (this._bloomEnabled) {
  68259. // Create down sample X4 post-process
  68260. this._createDownSampleX4PostProcess(scene, ratio / 2);
  68261. // Create bright pass post-process
  68262. this._createBrightPassPostProcess(scene, ratio / 2);
  68263. // Create gaussian blur post-processes (down sampling blurs)
  68264. this._createBlurPostProcesses(scene, ratio / 4, 1);
  68265. // Create texture adder post-process
  68266. this._createTextureAdderPostProcess(scene, ratio);
  68267. // Create depth-of-field source post-process
  68268. 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);
  68269. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  68270. }
  68271. if (this._lensFlareEnabled) {
  68272. // Create lens flare post-process
  68273. this._createLensFlarePostProcess(scene, ratio);
  68274. // Create depth-of-field source post-process post lens-flare and disable it now
  68275. 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);
  68276. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  68277. }
  68278. if (this._hdrEnabled) {
  68279. // Create luminance
  68280. this._createLuminancePostProcesses(scene, this._floatTextureType);
  68281. // Create HDR
  68282. this._createHdrPostProcess(scene, ratio);
  68283. // Create depth-of-field source post-process post hdr and disable it now
  68284. 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);
  68285. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  68286. }
  68287. if (this._depthOfFieldEnabled) {
  68288. // Create gaussian blur used by depth-of-field
  68289. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  68290. // Create depth-of-field post-process
  68291. this._createDepthOfFieldPostProcess(scene, ratio);
  68292. }
  68293. if (this._motionBlurEnabled) {
  68294. // Create motion blur post-process
  68295. this._createMotionBlurPostProcess(scene, ratio);
  68296. }
  68297. if (this._cameras !== null) {
  68298. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68299. }
  68300. };
  68301. // Down Sample X4 Post-Processs
  68302. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  68303. var _this = this;
  68304. var downSampleX4Offsets = new Array(32);
  68305. 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);
  68306. this.downSampleX4PostProcess.onApply = function (effect) {
  68307. var id = 0;
  68308. var width = _this.downSampleX4PostProcess.width;
  68309. var height = _this.downSampleX4PostProcess.height;
  68310. for (var i = -2; i < 2; i++) {
  68311. for (var j = -2; j < 2; j++) {
  68312. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  68313. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  68314. id += 2;
  68315. }
  68316. }
  68317. effect.setArray2("dsOffsets", downSampleX4Offsets);
  68318. };
  68319. // Add to pipeline
  68320. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  68321. };
  68322. // Brightpass Post-Process
  68323. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  68324. var _this = this;
  68325. var brightOffsets = new Array(8);
  68326. 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);
  68327. this.brightPassPostProcess.onApply = function (effect) {
  68328. var sU = (1.0 / _this.brightPassPostProcess.width);
  68329. var sV = (1.0 / _this.brightPassPostProcess.height);
  68330. brightOffsets[0] = -0.5 * sU;
  68331. brightOffsets[1] = 0.5 * sV;
  68332. brightOffsets[2] = 0.5 * sU;
  68333. brightOffsets[3] = 0.5 * sV;
  68334. brightOffsets[4] = -0.5 * sU;
  68335. brightOffsets[5] = -0.5 * sV;
  68336. brightOffsets[6] = 0.5 * sU;
  68337. brightOffsets[7] = -0.5 * sV;
  68338. effect.setArray2("dsOffsets", brightOffsets);
  68339. effect.setFloat("brightThreshold", _this.brightThreshold);
  68340. };
  68341. // Add to pipeline
  68342. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  68343. };
  68344. // Create blur H&V post-processes
  68345. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  68346. var _this = this;
  68347. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  68348. var engine = scene.getEngine();
  68349. 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);
  68350. 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);
  68351. blurX.onActivateObservable.add(function () {
  68352. var dw = blurX.width / engine.getRenderWidth();
  68353. blurX.kernel = _this[blurWidthKey] * dw;
  68354. });
  68355. blurY.onActivateObservable.add(function () {
  68356. var dw = blurY.height / engine.getRenderHeight();
  68357. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  68358. });
  68359. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  68360. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  68361. this.blurHPostProcesses.push(blurX);
  68362. this.blurVPostProcesses.push(blurY);
  68363. };
  68364. // Create texture adder post-process
  68365. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  68366. var _this = this;
  68367. 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);
  68368. this.textureAdderPostProcess.onApply = function (effect) {
  68369. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  68370. effect.setTexture("lensSampler", _this.lensTexture);
  68371. effect.setFloat("exposure", _this.exposure);
  68372. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  68373. };
  68374. // Add to pipeline
  68375. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  68376. };
  68377. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  68378. var _this = this;
  68379. var geometryRenderer = scene.enableGeometryBufferRenderer();
  68380. geometryRenderer.enablePosition = true;
  68381. var geometry = geometryRenderer.getGBuffer();
  68382. // Base post-process
  68383. 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));
  68384. var depthValues = BABYLON.Vector2.Zero();
  68385. this.volumetricLightPostProcess.onApply = function (effect) {
  68386. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  68387. var generator = _this.sourceLight.getShadowGenerator();
  68388. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  68389. effect.setTexture("positionSampler", geometry.textures[2]);
  68390. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  68391. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  68392. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  68393. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  68394. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  68395. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  68396. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  68397. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  68398. effect.setVector2("depthValues", depthValues);
  68399. }
  68400. };
  68401. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  68402. // Smooth
  68403. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  68404. // Merge
  68405. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  68406. this.volumetricLightMergePostProces.onApply = function (effect) {
  68407. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  68408. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  68409. };
  68410. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  68411. };
  68412. // Create luminance
  68413. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  68414. var _this = this;
  68415. // Create luminance
  68416. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  68417. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  68418. var offsets = [];
  68419. this.luminancePostProcess.onApply = function (effect) {
  68420. var sU = (1.0 / _this.luminancePostProcess.width);
  68421. var sV = (1.0 / _this.luminancePostProcess.height);
  68422. offsets[0] = -0.5 * sU;
  68423. offsets[1] = 0.5 * sV;
  68424. offsets[2] = 0.5 * sU;
  68425. offsets[3] = 0.5 * sV;
  68426. offsets[4] = -0.5 * sU;
  68427. offsets[5] = -0.5 * sV;
  68428. offsets[6] = 0.5 * sU;
  68429. offsets[7] = -0.5 * sV;
  68430. effect.setArray2("lumOffsets", offsets);
  68431. };
  68432. // Add to pipeline
  68433. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  68434. // Create down sample luminance
  68435. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  68436. var size = Math.pow(3, i);
  68437. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  68438. if (i === 0) {
  68439. defines += "#define FINAL_DOWN_SAMPLER";
  68440. }
  68441. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  68442. this.luminanceDownSamplePostProcesses.push(postProcess);
  68443. }
  68444. // Create callbacks and add effects
  68445. var lastLuminance = this.luminancePostProcess;
  68446. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  68447. var downSampleOffsets = new Array(18);
  68448. pp.onApply = function (effect) {
  68449. if (!lastLuminance) {
  68450. return;
  68451. }
  68452. var id = 0;
  68453. for (var x = -1; x < 2; x++) {
  68454. for (var y = -1; y < 2; y++) {
  68455. downSampleOffsets[id] = x / lastLuminance.width;
  68456. downSampleOffsets[id + 1] = y / lastLuminance.height;
  68457. id += 2;
  68458. }
  68459. }
  68460. effect.setArray2("dsOffsets", downSampleOffsets);
  68461. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  68462. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68463. lastLuminance = _this.luminancePostProcess;
  68464. }
  68465. else {
  68466. lastLuminance = pp;
  68467. }
  68468. };
  68469. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  68470. pp.onAfterRender = function (effect) {
  68471. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  68472. 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);
  68473. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  68474. };
  68475. }
  68476. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  68477. });
  68478. };
  68479. // Create HDR post-process
  68480. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  68481. var _this = this;
  68482. 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);
  68483. var outputLiminance = 1;
  68484. var time = 0;
  68485. var lastTime = 0;
  68486. this.hdrPostProcess.onApply = function (effect) {
  68487. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  68488. time += scene.getEngine().getDeltaTime();
  68489. if (outputLiminance < 0) {
  68490. outputLiminance = _this._hdrCurrentLuminance;
  68491. }
  68492. else {
  68493. var dt = (lastTime - time) / 1000.0;
  68494. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  68495. outputLiminance += _this.hdrDecreaseRate * dt;
  68496. }
  68497. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  68498. outputLiminance -= _this.hdrIncreaseRate * dt;
  68499. }
  68500. else {
  68501. outputLiminance = _this._hdrCurrentLuminance;
  68502. }
  68503. }
  68504. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  68505. effect.setFloat("averageLuminance", outputLiminance);
  68506. lastTime = time;
  68507. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  68508. };
  68509. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  68510. };
  68511. // Create lens flare post-process
  68512. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  68513. var _this = this;
  68514. 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);
  68515. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  68516. this._createBlurPostProcesses(scene, ratio / 4, 2);
  68517. 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);
  68518. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  68519. var resolution = new BABYLON.Vector2(0, 0);
  68520. // Lens flare
  68521. this.lensFlarePostProcess.onApply = function (effect) {
  68522. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  68523. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  68524. effect.setFloat("strength", _this.lensFlareStrength);
  68525. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  68526. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  68527. // Shift
  68528. resolution.x = _this.lensFlarePostProcess.width;
  68529. resolution.y = _this.lensFlarePostProcess.height;
  68530. effect.setVector2("resolution", resolution);
  68531. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  68532. };
  68533. // Compose
  68534. 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);
  68535. 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);
  68536. this.lensFlareComposePostProcess.onApply = function (effect) {
  68537. if (!_this._scene.activeCamera) {
  68538. return;
  68539. }
  68540. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68541. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  68542. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  68543. // Lens start rotation matrix
  68544. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  68545. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  68546. 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));
  68547. camRot *= 4.0;
  68548. 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);
  68549. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  68550. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  68551. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  68552. };
  68553. };
  68554. // Create depth-of-field post-process
  68555. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  68556. var _this = this;
  68557. 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);
  68558. this.depthOfFieldPostProcess.onApply = function (effect) {
  68559. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  68560. effect.setTexture("depthSampler", _this._getDepthTexture());
  68561. effect.setFloat("distance", _this.depthOfFieldDistance);
  68562. };
  68563. // Add to pipeline
  68564. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  68565. };
  68566. // Create motion blur post-process
  68567. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  68568. var _this = this;
  68569. 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);
  68570. var motionScale = 0;
  68571. var prevViewProjection = BABYLON.Matrix.Identity();
  68572. var invViewProjection = BABYLON.Matrix.Identity();
  68573. var viewProjection = BABYLON.Matrix.Identity();
  68574. var screenSize = BABYLON.Vector2.Zero();
  68575. this.motionBlurPostProcess.onApply = function (effect) {
  68576. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  68577. viewProjection.invertToRef(invViewProjection);
  68578. effect.setMatrix("inverseViewProjection", invViewProjection);
  68579. effect.setMatrix("prevViewProjection", prevViewProjection);
  68580. prevViewProjection = viewProjection;
  68581. screenSize.x = _this.motionBlurPostProcess.width;
  68582. screenSize.y = _this.motionBlurPostProcess.height;
  68583. effect.setVector2("screenSize", screenSize);
  68584. motionScale = scene.getEngine().getFps() / 60.0;
  68585. effect.setFloat("motionScale", motionScale);
  68586. effect.setFloat("motionStrength", _this.motionStrength);
  68587. effect.setTexture("depthSampler", _this._getDepthTexture());
  68588. };
  68589. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  68590. };
  68591. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  68592. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  68593. var renderer = this._scene.enableGeometryBufferRenderer();
  68594. return renderer.getGBuffer().textures[0];
  68595. }
  68596. return this._scene.enableDepthRenderer().getDepthMap();
  68597. };
  68598. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  68599. for (var i = 0; i < this._cameras.length; i++) {
  68600. var camera = this._cameras[i];
  68601. if (this.originalPostProcess) {
  68602. this.originalPostProcess.dispose(camera);
  68603. }
  68604. if (this.downSampleX4PostProcess) {
  68605. this.downSampleX4PostProcess.dispose(camera);
  68606. }
  68607. if (this.brightPassPostProcess) {
  68608. this.brightPassPostProcess.dispose(camera);
  68609. }
  68610. if (this.textureAdderPostProcess) {
  68611. this.textureAdderPostProcess.dispose(camera);
  68612. }
  68613. if (this.textureAdderFinalPostProcess) {
  68614. this.textureAdderFinalPostProcess.dispose(camera);
  68615. }
  68616. if (this.volumetricLightPostProcess) {
  68617. this.volumetricLightPostProcess.dispose(camera);
  68618. }
  68619. if (this.volumetricLightSmoothXPostProcess) {
  68620. this.volumetricLightSmoothXPostProcess.dispose(camera);
  68621. }
  68622. if (this.volumetricLightSmoothYPostProcess) {
  68623. this.volumetricLightSmoothYPostProcess.dispose(camera);
  68624. }
  68625. if (this.volumetricLightMergePostProces) {
  68626. this.volumetricLightMergePostProces.dispose(camera);
  68627. }
  68628. if (this.volumetricLightFinalPostProcess) {
  68629. this.volumetricLightFinalPostProcess.dispose(camera);
  68630. }
  68631. if (this.lensFlarePostProcess) {
  68632. this.lensFlarePostProcess.dispose(camera);
  68633. }
  68634. if (this.lensFlareComposePostProcess) {
  68635. this.lensFlareComposePostProcess.dispose(camera);
  68636. }
  68637. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  68638. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  68639. }
  68640. if (this.luminancePostProcess) {
  68641. this.luminancePostProcess.dispose(camera);
  68642. }
  68643. if (this.hdrPostProcess) {
  68644. this.hdrPostProcess.dispose(camera);
  68645. }
  68646. if (this.hdrFinalPostProcess) {
  68647. this.hdrFinalPostProcess.dispose(camera);
  68648. }
  68649. if (this.depthOfFieldPostProcess) {
  68650. this.depthOfFieldPostProcess.dispose(camera);
  68651. }
  68652. if (this.motionBlurPostProcess) {
  68653. this.motionBlurPostProcess.dispose(camera);
  68654. }
  68655. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  68656. this.blurHPostProcesses[j].dispose(camera);
  68657. }
  68658. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  68659. this.blurVPostProcesses[j].dispose(camera);
  68660. }
  68661. }
  68662. this.originalPostProcess = null;
  68663. this.downSampleX4PostProcess = null;
  68664. this.brightPassPostProcess = null;
  68665. this.textureAdderPostProcess = null;
  68666. this.textureAdderFinalPostProcess = null;
  68667. this.volumetricLightPostProcess = null;
  68668. this.volumetricLightSmoothXPostProcess = null;
  68669. this.volumetricLightSmoothYPostProcess = null;
  68670. this.volumetricLightMergePostProces = null;
  68671. this.volumetricLightFinalPostProcess = null;
  68672. this.lensFlarePostProcess = null;
  68673. this.lensFlareComposePostProcess = null;
  68674. this.luminancePostProcess = null;
  68675. this.hdrPostProcess = null;
  68676. this.hdrFinalPostProcess = null;
  68677. this.depthOfFieldPostProcess = null;
  68678. this.motionBlurPostProcess = null;
  68679. this.luminanceDownSamplePostProcesses = [];
  68680. this.blurHPostProcesses = [];
  68681. this.blurVPostProcesses = [];
  68682. };
  68683. // Dispose
  68684. StandardRenderingPipeline.prototype.dispose = function () {
  68685. this._disposePostProcesses();
  68686. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68687. _super.prototype.dispose.call(this);
  68688. };
  68689. // Serialize rendering pipeline
  68690. StandardRenderingPipeline.prototype.serialize = function () {
  68691. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68692. serializationObject.customType = "StandardRenderingPipeline";
  68693. return serializationObject;
  68694. };
  68695. /**
  68696. * Static members
  68697. */
  68698. // Parse serialized pipeline
  68699. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68700. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  68701. };
  68702. // Luminance steps
  68703. StandardRenderingPipeline.LuminanceSteps = 6;
  68704. __decorate([
  68705. BABYLON.serialize()
  68706. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  68707. __decorate([
  68708. BABYLON.serialize()
  68709. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  68710. __decorate([
  68711. BABYLON.serialize()
  68712. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  68713. __decorate([
  68714. BABYLON.serialize()
  68715. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  68716. __decorate([
  68717. BABYLON.serializeAsTexture("lensTexture")
  68718. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  68719. __decorate([
  68720. BABYLON.serialize()
  68721. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  68722. __decorate([
  68723. BABYLON.serialize()
  68724. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  68725. __decorate([
  68726. BABYLON.serialize()
  68727. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  68728. __decorate([
  68729. BABYLON.serialize()
  68730. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  68731. __decorate([
  68732. BABYLON.serialize()
  68733. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  68734. __decorate([
  68735. BABYLON.serialize()
  68736. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  68737. __decorate([
  68738. BABYLON.serializeAsTexture("lensColorTexture")
  68739. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  68740. __decorate([
  68741. BABYLON.serialize()
  68742. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  68743. __decorate([
  68744. BABYLON.serialize()
  68745. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  68746. __decorate([
  68747. BABYLON.serialize()
  68748. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  68749. __decorate([
  68750. BABYLON.serialize()
  68751. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  68752. __decorate([
  68753. BABYLON.serializeAsTexture("lensStarTexture")
  68754. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  68755. __decorate([
  68756. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  68757. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  68758. __decorate([
  68759. BABYLON.serialize()
  68760. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  68761. __decorate([
  68762. BABYLON.serialize()
  68763. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  68764. __decorate([
  68765. BABYLON.serialize()
  68766. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  68767. __decorate([
  68768. BABYLON.serialize()
  68769. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  68770. __decorate([
  68771. BABYLON.serialize()
  68772. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  68773. __decorate([
  68774. BABYLON.serialize()
  68775. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  68776. __decorate([
  68777. BABYLON.serialize()
  68778. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  68779. __decorate([
  68780. BABYLON.serialize()
  68781. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  68782. __decorate([
  68783. BABYLON.serialize()
  68784. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  68785. __decorate([
  68786. BABYLON.serialize()
  68787. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  68788. __decorate([
  68789. BABYLON.serialize()
  68790. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  68791. __decorate([
  68792. BABYLON.serialize()
  68793. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  68794. return StandardRenderingPipeline;
  68795. }(BABYLON.PostProcessRenderPipeline));
  68796. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  68797. })(BABYLON || (BABYLON = {}));
  68798. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  68799. "use strict";
  68800. var BABYLON;
  68801. (function (BABYLON) {
  68802. var FxaaPostProcess = /** @class */ (function (_super) {
  68803. __extends(FxaaPostProcess, _super);
  68804. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68805. if (camera === void 0) { camera = null; }
  68806. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68807. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  68808. _this.onApplyObservable.add(function (effect) {
  68809. var texelSize = _this.texelSize;
  68810. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  68811. });
  68812. return _this;
  68813. }
  68814. return FxaaPostProcess;
  68815. }(BABYLON.PostProcess));
  68816. BABYLON.FxaaPostProcess = FxaaPostProcess;
  68817. })(BABYLON || (BABYLON = {}));
  68818. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  68819. "use strict";
  68820. var BABYLON;
  68821. (function (BABYLON) {
  68822. /**
  68823. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  68824. */
  68825. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  68826. __extends(ChromaticAberrationPostProcess, _super);
  68827. /**
  68828. * Creates a new instance of @see ChromaticAberrationPostProcess
  68829. * @param name The name of the effect.
  68830. * @param screenWidth The width of the screen to apply the effect on.
  68831. * @param screenHeight The height of the screen to apply the effect on.
  68832. * @param options The required width/height ratio to downsize to before computing the render pass.
  68833. * @param camera The camera to apply the render pass to.
  68834. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68835. * @param engine The engine which the post process will be applied. (default: current engine)
  68836. * @param reusable If the post process can be reused on the same frame. (default: false)
  68837. * @param textureType Type of textures used when performing the post process. (default: 0)
  68838. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68839. */
  68840. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68841. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68842. if (blockCompilation === void 0) { blockCompilation = false; }
  68843. var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68844. /**
  68845. * The amount of seperation of rgb channels (default: 30)
  68846. */
  68847. _this.aberrationAmount = 30;
  68848. /**
  68849. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  68850. */
  68851. _this.radialIntensity = 0;
  68852. /**
  68853. * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
  68854. */
  68855. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  68856. /**
  68857. * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
  68858. */
  68859. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  68860. _this.onApplyObservable.add(function (effect) {
  68861. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  68862. effect.setFloat('screen_width', screenWidth);
  68863. effect.setFloat('screen_height', screenHeight);
  68864. effect.setFloat('radialIntensity', _this.radialIntensity);
  68865. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  68866. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  68867. });
  68868. return _this;
  68869. }
  68870. return ChromaticAberrationPostProcess;
  68871. }(BABYLON.PostProcess));
  68872. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  68873. })(BABYLON || (BABYLON = {}));
  68874. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  68875. "use strict";
  68876. var BABYLON;
  68877. (function (BABYLON) {
  68878. /**
  68879. * The SharpenPostProcess applies a sharpen kernel to every pixel
  68880. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68881. */
  68882. var SharpenPostProcess = /** @class */ (function (_super) {
  68883. __extends(SharpenPostProcess, _super);
  68884. /**
  68885. * Creates a new instance of @see ConvolutionPostProcess
  68886. * @param name The name of the effect.
  68887. * @param options The required width/height ratio to downsize to before computing the render pass.
  68888. * @param camera The camera to apply the render pass to.
  68889. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68890. * @param engine The engine which the post process will be applied. (default: current engine)
  68891. * @param reusable If the post process can be reused on the same frame. (default: false)
  68892. * @param textureType Type of textures used when performing the post process. (default: 0)
  68893. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68894. */
  68895. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68896. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68897. if (blockCompilation === void 0) { blockCompilation = false; }
  68898. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  68899. /**
  68900. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  68901. */
  68902. _this.colorAmount = 1.0;
  68903. /**
  68904. * How much sharpness should be applied (default: 0.3)
  68905. */
  68906. _this.edgeAmount = 0.3;
  68907. _this.onApply = function (effect) {
  68908. effect.setFloat2("screenSize", _this.width, _this.height);
  68909. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  68910. };
  68911. return _this;
  68912. }
  68913. return SharpenPostProcess;
  68914. }(BABYLON.PostProcess));
  68915. BABYLON.SharpenPostProcess = SharpenPostProcess;
  68916. })(BABYLON || (BABYLON = {}));
  68917. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  68918. "use strict";
  68919. var BABYLON;
  68920. (function (BABYLON) {
  68921. /**
  68922. * The Blur Post Process which blurs an image based on a kernel and direction.
  68923. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68924. */
  68925. var BlurPostProcess = /** @class */ (function (_super) {
  68926. __extends(BlurPostProcess, _super);
  68927. /**
  68928. * Creates a new instance of @see BlurPostProcess
  68929. * @param name The name of the effect.
  68930. * @param direction The direction in which to blur the image.
  68931. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
  68932. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68933. * @param camera The camera to apply the render pass to.
  68934. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68935. * @param engine The engine which the post process will be applied. (default: current engine)
  68936. * @param reusable If the post process can be reused on the same frame. (default: false)
  68937. * @param textureType Type of textures used when performing the post process. (default: 0)
  68938. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  68939. */
  68940. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  68941. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68942. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68943. if (defines === void 0) { defines = ""; }
  68944. if (blockCompilation === void 0) { blockCompilation = false; }
  68945. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  68946. _this.direction = direction;
  68947. _this.blockCompilation = blockCompilation;
  68948. _this._packedFloat = false;
  68949. _this._staticDefines = "";
  68950. _this._staticDefines = defines;
  68951. _this.onApplyObservable.add(function (effect) {
  68952. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68953. });
  68954. _this.kernel = kernel;
  68955. return _this;
  68956. }
  68957. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68958. /**
  68959. * Gets the length in pixels of the blur sample region
  68960. */
  68961. get: function () {
  68962. return this._idealKernel;
  68963. },
  68964. /**
  68965. * Sets the length in pixels of the blur sample region
  68966. */
  68967. set: function (v) {
  68968. if (this._idealKernel === v) {
  68969. return;
  68970. }
  68971. v = Math.max(v, 1);
  68972. this._idealKernel = v;
  68973. this._kernel = this._nearestBestKernel(v);
  68974. if (!this.blockCompilation) {
  68975. this._updateParameters();
  68976. }
  68977. },
  68978. enumerable: true,
  68979. configurable: true
  68980. });
  68981. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68982. /**
  68983. * Gets wether or not the blur is unpacking/repacking floats
  68984. */
  68985. get: function () {
  68986. return this._packedFloat;
  68987. },
  68988. /**
  68989. * Sets wether or not the blur needs to unpack/repack floats
  68990. */
  68991. set: function (v) {
  68992. if (this._packedFloat === v) {
  68993. return;
  68994. }
  68995. this._packedFloat = v;
  68996. if (!this.blockCompilation) {
  68997. this._updateParameters();
  68998. }
  68999. },
  69000. enumerable: true,
  69001. configurable: true
  69002. });
  69003. /**
  69004. * Updates the effect with the current post process compile time values and recompiles the shader.
  69005. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69006. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69007. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69008. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  69009. * @param onCompiled Called when the shader has been compiled.
  69010. * @param onError Called if there is an error when compiling a shader.
  69011. */
  69012. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69013. if (defines === void 0) { defines = null; }
  69014. if (uniforms === void 0) { uniforms = null; }
  69015. if (samplers === void 0) { samplers = null; }
  69016. this._updateParameters(onCompiled, onError);
  69017. };
  69018. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  69019. // Generate sampling offsets and weights
  69020. var N = this._kernel;
  69021. var centerIndex = (N - 1) / 2;
  69022. // Generate Gaussian sampling weights over kernel
  69023. var offsets = [];
  69024. var weights = [];
  69025. var totalWeight = 0;
  69026. for (var i = 0; i < N; i++) {
  69027. var u = i / (N - 1);
  69028. var w = this._gaussianWeight(u * 2.0 - 1);
  69029. offsets[i] = (i - centerIndex);
  69030. weights[i] = w;
  69031. totalWeight += w;
  69032. }
  69033. // Normalize weights
  69034. for (var i = 0; i < weights.length; i++) {
  69035. weights[i] /= totalWeight;
  69036. }
  69037. // Optimize: combine samples to take advantage of hardware linear sampling
  69038. // Walk from left to center, combining pairs (symmetrically)
  69039. var linearSamplingWeights = [];
  69040. var linearSamplingOffsets = [];
  69041. var linearSamplingMap = [];
  69042. for (var i = 0; i <= centerIndex; i += 2) {
  69043. var j = Math.min(i + 1, Math.floor(centerIndex));
  69044. var singleCenterSample = i === j;
  69045. if (singleCenterSample) {
  69046. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69047. }
  69048. else {
  69049. var sharedCell = j === centerIndex;
  69050. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69051. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69052. if (offsetLinear === 0) {
  69053. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69054. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69055. }
  69056. else {
  69057. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69058. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69059. }
  69060. }
  69061. }
  69062. for (var i = 0; i < linearSamplingMap.length; i++) {
  69063. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69064. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69065. }
  69066. // Replace with optimized
  69067. offsets = linearSamplingOffsets;
  69068. weights = linearSamplingWeights;
  69069. // Generate shaders
  69070. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69071. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69072. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69073. var defines = "";
  69074. defines += this._staticDefines;
  69075. for (var i = 0; i < varyingCount; i++) {
  69076. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69077. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69078. }
  69079. var depCount = 0;
  69080. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69081. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69082. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69083. depCount++;
  69084. }
  69085. if (this.packedFloat) {
  69086. defines += "#define PACKEDFLOAT 1";
  69087. }
  69088. _super.prototype.updateEffect.call(this, defines, null, null, {
  69089. varyingCount: varyingCount,
  69090. depCount: depCount
  69091. }, onCompiled, onError);
  69092. };
  69093. /**
  69094. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69095. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69096. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69097. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69098. * The gaps between physical kernels are compensated for in the weighting of the samples
  69099. * @param idealKernel Ideal blur kernel.
  69100. * @return Nearest best kernel.
  69101. */
  69102. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69103. var v = Math.round(idealKernel);
  69104. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69105. var k = _a[_i];
  69106. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69107. return Math.max(k, 3);
  69108. }
  69109. }
  69110. return Math.max(v, 3);
  69111. };
  69112. /**
  69113. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69114. * @param x The point on the Gaussian distribution to sample.
  69115. * @return the value of the Gaussian function at x.
  69116. */
  69117. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69118. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69119. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69120. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69121. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69122. // truncated at around 1.3% of peak strength.
  69123. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69124. var sigma = (1 / 3);
  69125. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69126. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69127. var weight = (1.0 / denominator) * Math.exp(exponent);
  69128. return weight;
  69129. };
  69130. /**
  69131. * Generates a string that can be used as a floating point number in GLSL.
  69132. * @param x Value to print.
  69133. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69134. * @return GLSL float string.
  69135. */
  69136. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69137. if (decimalFigures === void 0) { decimalFigures = 8; }
  69138. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69139. };
  69140. return BlurPostProcess;
  69141. }(BABYLON.PostProcess));
  69142. BABYLON.BlurPostProcess = BlurPostProcess;
  69143. })(BABYLON || (BABYLON = {}));
  69144. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69145. "use strict";
  69146. var BABYLON;
  69147. (function (BABYLON) {
  69148. /**
  69149. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69150. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69151. * based on samples that have a large difference in distance than the center pixel.
  69152. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69153. */
  69154. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69155. __extends(DepthOfFieldBlurPostProcess, _super);
  69156. /**
  69157. * Creates a new instance of @see CircleOfConfusionPostProcess
  69158. * @param name The name of the effect.
  69159. * @param scene The scene the effect belongs to.
  69160. * @param direction The direction the blur should be applied.
  69161. * @param kernel The size of the kernel used to blur.
  69162. * @param options The required width/height ratio to downsize to before computing the render pass.
  69163. * @param camera The camera to apply the render pass to.
  69164. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69165. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69166. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69167. * @param engine The engine which the post process will be applied. (default: current engine)
  69168. * @param reusable If the post process can be reused on the same frame. (default: false)
  69169. * @param textureType Type of textures used when performing the post process. (default: 0)
  69170. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69171. */
  69172. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  69173. if (imageToBlur === void 0) { imageToBlur = null; }
  69174. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69175. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69176. if (blockCompilation === void 0) { blockCompilation = false; }
  69177. var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
  69178. _this.direction = direction;
  69179. _this.onApplyObservable.add(function (effect) {
  69180. if (imageToBlur != null) {
  69181. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69182. }
  69183. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  69184. if (scene.activeCamera) {
  69185. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69186. }
  69187. });
  69188. return _this;
  69189. }
  69190. return DepthOfFieldBlurPostProcess;
  69191. }(BABYLON.BlurPostProcess));
  69192. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69193. })(BABYLON || (BABYLON = {}));
  69194. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69195. "use strict";
  69196. var BABYLON;
  69197. (function (BABYLON) {
  69198. /**
  69199. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  69200. */
  69201. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  69202. __extends(DepthOfFieldMergePostProcess, _super);
  69203. /**
  69204. * Creates a new instance of @see CircleOfConfusionPostProcess
  69205. * @param name The name of the effect.
  69206. * @param original The non-blurred image to be modified
  69207. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  69208. * @param blurSteps Incrimental bluring post processes.
  69209. * @param options The required width/height ratio to downsize to before computing the render pass.
  69210. * @param camera The camera to apply the render pass to.
  69211. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69212. * @param engine The engine which the post process will be applied. (default: current engine)
  69213. * @param reusable If the post process can be reused on the same frame. (default: false)
  69214. * @param textureType Type of textures used when performing the post process. (default: 0)
  69215. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69216. */
  69217. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69218. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69219. if (blockCompilation === void 0) { blockCompilation = false; }
  69220. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  69221. _this.blurSteps = blurSteps;
  69222. _this.onApplyObservable.add(function (effect) {
  69223. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  69224. effect.setTextureFromPostProcess("textureSampler", original);
  69225. blurSteps.forEach(function (step, index) {
  69226. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  69227. });
  69228. });
  69229. if (!blockCompilation) {
  69230. _this.updateEffect();
  69231. }
  69232. return _this;
  69233. }
  69234. /**
  69235. * Updates the effect with the current post process compile time values and recompiles the shader.
  69236. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69237. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69238. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69239. * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
  69240. * @param onCompiled Called when the shader has been compiled.
  69241. * @param onError Called if there is an error when compiling a shader.
  69242. */
  69243. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69244. if (defines === void 0) { defines = null; }
  69245. if (uniforms === void 0) { uniforms = null; }
  69246. if (samplers === void 0) { samplers = null; }
  69247. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  69248. };
  69249. return DepthOfFieldMergePostProcess;
  69250. }(BABYLON.PostProcess));
  69251. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  69252. })(BABYLON || (BABYLON = {}));
  69253. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  69254. "use strict";
  69255. var BABYLON;
  69256. (function (BABYLON) {
  69257. /**
  69258. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  69259. */
  69260. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  69261. __extends(CircleOfConfusionPostProcess, _super);
  69262. /**
  69263. * Creates a new instance of @see CircleOfConfusionPostProcess
  69264. * @param name The name of the effect.
  69265. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
  69266. * @param options The required width/height ratio to downsize to before computing the render pass.
  69267. * @param camera The camera to apply the render pass to.
  69268. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69269. * @param engine The engine which the post process will be applied. (default: current engine)
  69270. * @param reusable If the post process can be reused on the same frame. (default: false)
  69271. * @param textureType Type of textures used when performing the post process. (default: 0)
  69272. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69273. */
  69274. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69275. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69276. if (blockCompilation === void 0) { blockCompilation = false; }
  69277. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69278. /**
  69279. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  69280. */
  69281. _this.lensSize = 50;
  69282. /**
  69283. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69284. */
  69285. _this.fStop = 1.4;
  69286. /**
  69287. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69288. */
  69289. _this.focusDistance = 2000;
  69290. /**
  69291. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  69292. */
  69293. _this.focalLength = 50;
  69294. _this._depthTexture = null;
  69295. _this._depthTexture = depthTexture;
  69296. _this.onApplyObservable.add(function (effect) {
  69297. if (!_this._depthTexture) {
  69298. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  69299. return;
  69300. }
  69301. effect.setTexture("depthSampler", _this._depthTexture);
  69302. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  69303. var aperture = _this.lensSize / _this.fStop;
  69304. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  69305. effect.setFloat('focusDistance', _this.focusDistance);
  69306. effect.setFloat('cocPrecalculation', cocPrecalculation);
  69307. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  69308. });
  69309. return _this;
  69310. }
  69311. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  69312. /**
  69313. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  69314. */
  69315. set: function (value) {
  69316. this._depthTexture = value;
  69317. },
  69318. enumerable: true,
  69319. configurable: true
  69320. });
  69321. return CircleOfConfusionPostProcess;
  69322. }(BABYLON.PostProcess));
  69323. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  69324. })(BABYLON || (BABYLON = {}));
  69325. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  69326. "use strict";
  69327. var BABYLON;
  69328. (function (BABYLON) {
  69329. /**
  69330. * Specifies the level of max blur that should be applied when using the depth of field effect
  69331. */
  69332. var DepthOfFieldEffectBlurLevel;
  69333. (function (DepthOfFieldEffectBlurLevel) {
  69334. /**
  69335. * Subtle blur
  69336. */
  69337. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  69338. /**
  69339. * Medium blur
  69340. */
  69341. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  69342. /**
  69343. * Large blur
  69344. */
  69345. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  69346. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  69347. ;
  69348. /**
  69349. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  69350. */
  69351. var DepthOfFieldEffect = /** @class */ (function (_super) {
  69352. __extends(DepthOfFieldEffect, _super);
  69353. /**
  69354. * Creates a new instance of @see DepthOfFieldEffect
  69355. * @param scene The scene the effect belongs to.
  69356. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
  69357. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  69358. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  69359. */
  69360. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  69361. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  69362. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  69363. if (blockCompilation === void 0) { blockCompilation = false; }
  69364. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  69365. return _this._effects;
  69366. }, true) || this;
  69367. _this._effects = [];
  69368. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  69369. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69370. // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
  69371. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  69372. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69373. _this._depthOfFieldBlurY = [];
  69374. _this._depthOfFieldBlurX = [];
  69375. var blurCount = 1;
  69376. var kernelSize = 15;
  69377. switch (blurLevel) {
  69378. case DepthOfFieldEffectBlurLevel.High: {
  69379. blurCount = 3;
  69380. kernelSize = 51;
  69381. break;
  69382. }
  69383. case DepthOfFieldEffectBlurLevel.Medium: {
  69384. blurCount = 2;
  69385. kernelSize = 31;
  69386. break;
  69387. }
  69388. default: {
  69389. kernelSize = 15;
  69390. blurCount = 1;
  69391. break;
  69392. }
  69393. }
  69394. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  69395. for (var i = 0; i < blurCount; i++) {
  69396. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69397. blurY.autoClear = false;
  69398. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69399. blurX.autoClear = false;
  69400. _this._depthOfFieldBlurY.push(blurY);
  69401. _this._depthOfFieldBlurX.push(blurX);
  69402. }
  69403. // Merge blurred images with original image based on circleOfConfusion
  69404. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  69405. _this._depthOfFieldMerge.autoClear = false;
  69406. // Set all post processes on the effect.
  69407. _this._effects = [_this._circleOfConfusion];
  69408. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  69409. _this._effects.push(_this._depthOfFieldBlurY[i]);
  69410. _this._effects.push(_this._depthOfFieldBlurX[i]);
  69411. }
  69412. _this._effects.push(_this._depthOfFieldMerge);
  69413. return _this;
  69414. }
  69415. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  69416. get: function () {
  69417. return this._circleOfConfusion.focalLength;
  69418. },
  69419. /**
  69420. * The focal the length of the camera used in the effect
  69421. */
  69422. set: function (value) {
  69423. this._circleOfConfusion.focalLength = value;
  69424. },
  69425. enumerable: true,
  69426. configurable: true
  69427. });
  69428. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  69429. get: function () {
  69430. return this._circleOfConfusion.fStop;
  69431. },
  69432. /**
  69433. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69434. */
  69435. set: function (value) {
  69436. this._circleOfConfusion.fStop = value;
  69437. },
  69438. enumerable: true,
  69439. configurable: true
  69440. });
  69441. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  69442. get: function () {
  69443. return this._circleOfConfusion.focusDistance;
  69444. },
  69445. /**
  69446. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69447. */
  69448. set: function (value) {
  69449. this._circleOfConfusion.focusDistance = value;
  69450. },
  69451. enumerable: true,
  69452. configurable: true
  69453. });
  69454. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  69455. get: function () {
  69456. return this._circleOfConfusion.lensSize;
  69457. },
  69458. /**
  69459. * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
  69460. */
  69461. set: function (value) {
  69462. this._circleOfConfusion.lensSize = value;
  69463. },
  69464. enumerable: true,
  69465. configurable: true
  69466. });
  69467. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  69468. /**
  69469. * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
  69470. */
  69471. set: function (value) {
  69472. this._circleOfConfusion.depthTexture = value;
  69473. },
  69474. enumerable: true,
  69475. configurable: true
  69476. });
  69477. /**
  69478. * Disposes each of the internal effects for a given camera.
  69479. * @param camera The camera to dispose the effect on.
  69480. */
  69481. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  69482. this._circleOfConfusion.dispose(camera);
  69483. this._depthOfFieldBlurX.forEach(function (element) {
  69484. element.dispose(camera);
  69485. });
  69486. this._depthOfFieldBlurY.forEach(function (element) {
  69487. element.dispose(camera);
  69488. });
  69489. this._depthOfFieldMerge.dispose(camera);
  69490. };
  69491. /**
  69492. * Internal
  69493. */
  69494. DepthOfFieldEffect.prototype._updateEffects = function () {
  69495. for (var effect in this._effects) {
  69496. this._effects[effect].updateEffect();
  69497. }
  69498. };
  69499. /**
  69500. * Internal
  69501. * @returns if all the contained post processes are ready.
  69502. */
  69503. DepthOfFieldEffect.prototype._isReady = function () {
  69504. for (var effect in this._effects) {
  69505. if (!this._effects[effect].isReady()) {
  69506. return false;
  69507. }
  69508. }
  69509. return true;
  69510. };
  69511. return DepthOfFieldEffect;
  69512. }(BABYLON.PostProcessRenderEffect));
  69513. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  69514. })(BABYLON || (BABYLON = {}));
  69515. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  69516. "use strict";
  69517. var BABYLON;
  69518. (function (BABYLON) {
  69519. /**
  69520. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  69521. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  69522. */
  69523. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  69524. __extends(DefaultRenderingPipeline, _super);
  69525. /**
  69526. * @constructor
  69527. * @param {string} name - The rendering pipeline name
  69528. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69529. * @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)
  69530. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69531. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  69532. */
  69533. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  69534. if (automaticBuild === void 0) { automaticBuild = true; }
  69535. var _this = _super.call(this, scene.getEngine(), name) || this;
  69536. _this._originalCameras = [];
  69537. /**
  69538. * ID of the sharpen post process,
  69539. */
  69540. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  69541. /**
  69542. * ID of the pass post process used for bloom,
  69543. */
  69544. _this.PassPostProcessId = "PassPostProcessEffect";
  69545. /**
  69546. * ID of the highlight post process used for bloom,
  69547. */
  69548. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  69549. /**
  69550. * ID of the blurX post process used for bloom,
  69551. */
  69552. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  69553. /**
  69554. * ID of the blurY post process used for bloom,
  69555. */
  69556. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  69557. /**
  69558. * ID of the copy back post process used for bloom,
  69559. */
  69560. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  69561. /**
  69562. * ID of the image processing post process;
  69563. */
  69564. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  69565. /**
  69566. * ID of the Fast Approximate Anti-Aliasing post process;
  69567. */
  69568. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  69569. /**
  69570. * ID of the final merge post process;
  69571. */
  69572. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  69573. /**
  69574. * ID of the chromatic aberration post process,
  69575. */
  69576. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  69577. /**
  69578. * Animations which can be used to tweak settings over a period of time
  69579. */
  69580. _this.animations = [];
  69581. // Values
  69582. _this._sharpenEnabled = false;
  69583. _this._bloomEnabled = false;
  69584. _this._depthOfFieldEnabled = false;
  69585. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  69586. _this._fxaaEnabled = false;
  69587. _this._msaaEnabled = false;
  69588. _this._imageProcessingEnabled = true;
  69589. _this._bloomScale = 0.6;
  69590. _this._chromaticAberrationEnabled = false;
  69591. _this._buildAllowed = true;
  69592. /**
  69593. * Specifies the size of the bloom blur kernel, relative to the final output size
  69594. */
  69595. _this.bloomKernel = 64;
  69596. /**
  69597. * Specifies the weight of the bloom in the final rendering
  69598. */
  69599. _this._bloomWeight = 0.15;
  69600. _this._prevPostProcess = null;
  69601. _this._prevPrevPostProcess = null;
  69602. _this._cameras = cameras || [];
  69603. _this._originalCameras = _this._cameras.slice();
  69604. _this._buildAllowed = automaticBuild;
  69605. // Initialize
  69606. _this._scene = scene;
  69607. var caps = _this._scene.getEngine().getCaps();
  69608. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  69609. // Misc
  69610. if (_this._hdr) {
  69611. if (caps.textureHalfFloatRender) {
  69612. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69613. }
  69614. else if (caps.textureFloatRender) {
  69615. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69616. }
  69617. }
  69618. else {
  69619. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69620. }
  69621. // Attach
  69622. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69623. var engine = _this._scene.getEngine();
  69624. // Create post processes before hand so they can be modified before enabled.
  69625. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  69626. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69627. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  69628. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  69629. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  69630. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  69631. _this._buildPipeline();
  69632. return _this;
  69633. }
  69634. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  69635. get: function () {
  69636. return this._sharpenEnabled;
  69637. },
  69638. /**
  69639. * Enable or disable the sharpen process from the pipeline
  69640. */
  69641. set: function (enabled) {
  69642. if (this._sharpenEnabled === enabled) {
  69643. return;
  69644. }
  69645. this._sharpenEnabled = enabled;
  69646. this._buildPipeline();
  69647. },
  69648. enumerable: true,
  69649. configurable: true
  69650. });
  69651. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  69652. get: function () {
  69653. return this._bloomWeight;
  69654. },
  69655. /**
  69656. * The strength of the bloom.
  69657. */
  69658. set: function (value) {
  69659. if (this._bloomWeight === value) {
  69660. return;
  69661. }
  69662. this._bloomWeight = value;
  69663. if (this._hdr && this.copyBack) {
  69664. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  69665. }
  69666. },
  69667. enumerable: true,
  69668. configurable: true
  69669. });
  69670. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  69671. get: function () {
  69672. return this._bloomScale;
  69673. },
  69674. /**
  69675. * The scale of the bloom, lower value will provide better performance.
  69676. */
  69677. set: function (value) {
  69678. if (this._bloomScale === value) {
  69679. return;
  69680. }
  69681. this._bloomScale = value;
  69682. this._buildPipeline();
  69683. },
  69684. enumerable: true,
  69685. configurable: true
  69686. });
  69687. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  69688. get: function () {
  69689. return this._bloomEnabled;
  69690. },
  69691. /**
  69692. * Enable or disable the bloom from the pipeline
  69693. */
  69694. set: function (enabled) {
  69695. if (this._bloomEnabled === enabled) {
  69696. return;
  69697. }
  69698. this._bloomEnabled = enabled;
  69699. this._buildPipeline();
  69700. },
  69701. enumerable: true,
  69702. configurable: true
  69703. });
  69704. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  69705. /**
  69706. * If the depth of field is enabled.
  69707. */
  69708. get: function () {
  69709. return this._depthOfFieldEnabled;
  69710. },
  69711. set: function (enabled) {
  69712. if (this._depthOfFieldEnabled === enabled) {
  69713. return;
  69714. }
  69715. this._depthOfFieldEnabled = enabled;
  69716. this._buildPipeline();
  69717. },
  69718. enumerable: true,
  69719. configurable: true
  69720. });
  69721. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  69722. /**
  69723. * Blur level of the depth of field effect. (Higher blur will effect performance)
  69724. */
  69725. get: function () {
  69726. return this._depthOfFieldBlurLevel;
  69727. },
  69728. set: function (value) {
  69729. if (this._depthOfFieldBlurLevel === value) {
  69730. return;
  69731. }
  69732. this._depthOfFieldBlurLevel = value;
  69733. // recreate dof and dispose old as this setting is not dynamic
  69734. var oldDof = this.depthOfField;
  69735. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  69736. this.depthOfField.focalLength = oldDof.focalLength;
  69737. this.depthOfField.focusDistance = oldDof.focusDistance;
  69738. this.depthOfField.fStop = oldDof.fStop;
  69739. this.depthOfField.lensSize = oldDof.lensSize;
  69740. for (var i = 0; i < this._cameras.length; i++) {
  69741. oldDof.disposeEffects(this._cameras[i]);
  69742. }
  69743. this._buildPipeline();
  69744. },
  69745. enumerable: true,
  69746. configurable: true
  69747. });
  69748. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  69749. get: function () {
  69750. return this._fxaaEnabled;
  69751. },
  69752. /**
  69753. * If the anti aliasing is enabled.
  69754. */
  69755. set: function (enabled) {
  69756. if (this._fxaaEnabled === enabled) {
  69757. return;
  69758. }
  69759. this._fxaaEnabled = enabled;
  69760. this._buildPipeline();
  69761. },
  69762. enumerable: true,
  69763. configurable: true
  69764. });
  69765. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  69766. get: function () {
  69767. return this._msaaEnabled;
  69768. },
  69769. /**
  69770. * If the multisample anti-aliasing is enabled.
  69771. */
  69772. set: function (enabled) {
  69773. if (this._msaaEnabled === enabled) {
  69774. return;
  69775. }
  69776. this._msaaEnabled = enabled;
  69777. this._buildPipeline();
  69778. },
  69779. enumerable: true,
  69780. configurable: true
  69781. });
  69782. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  69783. get: function () {
  69784. return this._imageProcessingEnabled;
  69785. },
  69786. /**
  69787. * If image processing is enabled.
  69788. */
  69789. set: function (enabled) {
  69790. if (this._imageProcessingEnabled === enabled) {
  69791. return;
  69792. }
  69793. this._imageProcessingEnabled = enabled;
  69794. this._buildPipeline();
  69795. },
  69796. enumerable: true,
  69797. configurable: true
  69798. });
  69799. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  69800. get: function () {
  69801. return this._chromaticAberrationEnabled;
  69802. },
  69803. /**
  69804. * Enable or disable the chromaticAberration process from the pipeline
  69805. */
  69806. set: function (enabled) {
  69807. if (this._chromaticAberrationEnabled === enabled) {
  69808. return;
  69809. }
  69810. this._chromaticAberrationEnabled = enabled;
  69811. this._buildPipeline();
  69812. },
  69813. enumerable: true,
  69814. configurable: true
  69815. });
  69816. /**
  69817. * Force the compilation of the entire pipeline.
  69818. */
  69819. DefaultRenderingPipeline.prototype.prepare = function () {
  69820. var previousState = this._buildAllowed;
  69821. this._buildAllowed = true;
  69822. this._buildPipeline();
  69823. this._buildAllowed = previousState;
  69824. };
  69825. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  69826. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  69827. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  69828. postProcess.autoClear = false;
  69829. }
  69830. else {
  69831. postProcess.autoClear = true;
  69832. }
  69833. if (!skipTextureSharing) {
  69834. if (this._prevPrevPostProcess) {
  69835. postProcess.shareOutputWith(this._prevPrevPostProcess);
  69836. }
  69837. else {
  69838. postProcess.useOwnOutput();
  69839. }
  69840. if (this._prevPostProcess) {
  69841. this._prevPrevPostProcess = this._prevPostProcess;
  69842. }
  69843. this._prevPostProcess = postProcess;
  69844. }
  69845. };
  69846. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  69847. var _this = this;
  69848. if (!this._buildAllowed) {
  69849. return;
  69850. }
  69851. var engine = this._scene.getEngine();
  69852. this._disposePostProcesses();
  69853. if (this._cameras !== null) {
  69854. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69855. // get back cameras to be used to reattach pipeline
  69856. this._cameras = this._originalCameras.slice();
  69857. }
  69858. this._reset();
  69859. this._prevPostProcess = null;
  69860. this._prevPrevPostProcess = null;
  69861. if (this.sharpenEnabled) {
  69862. if (!this.sharpen.isReady()) {
  69863. this.sharpen.updateEffect();
  69864. }
  69865. this.addEffect(this._sharpenEffect);
  69866. this._setAutoClearAndTextureSharing(this.sharpen);
  69867. }
  69868. if (this.depthOfFieldEnabled) {
  69869. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  69870. this.depthOfField.depthTexture = depthTexture;
  69871. if (!this.depthOfField._isReady()) {
  69872. this.depthOfField._updateEffects();
  69873. }
  69874. this.addEffect(this.depthOfField);
  69875. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  69876. }
  69877. if (this.bloomEnabled) {
  69878. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69879. this._setAutoClearAndTextureSharing(this.pass, true);
  69880. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  69881. if (!this._hdr) {
  69882. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69883. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  69884. this.highlights.autoClear = false;
  69885. this.highlights.alwaysForcePOT = true;
  69886. }
  69887. 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);
  69888. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  69889. this.blurX.alwaysForcePOT = true;
  69890. this.blurX.autoClear = false;
  69891. this.blurX.onActivateObservable.add(function () {
  69892. var dw = _this.blurX.width / engine.getRenderWidth(true);
  69893. _this.blurX.kernel = _this.bloomKernel * dw;
  69894. });
  69895. 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);
  69896. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  69897. this.blurY.alwaysForcePOT = true;
  69898. this.blurY.autoClear = false;
  69899. this.blurY.onActivateObservable.add(function () {
  69900. var dh = _this.blurY.height / engine.getRenderHeight(true);
  69901. _this.blurY.kernel = _this.bloomKernel * dh;
  69902. });
  69903. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69904. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  69905. this.copyBack.alwaysForcePOT = true;
  69906. if (this._hdr) {
  69907. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  69908. var w = this.bloomWeight;
  69909. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  69910. }
  69911. else {
  69912. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  69913. }
  69914. this.copyBack.autoClear = false;
  69915. }
  69916. if (this._imageProcessingEnabled) {
  69917. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69918. if (this._hdr) {
  69919. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  69920. }
  69921. else {
  69922. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  69923. }
  69924. }
  69925. if (this._hdr && this.imageProcessing) {
  69926. this.finalMerge = this.imageProcessing;
  69927. }
  69928. else {
  69929. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69930. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  69931. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  69932. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  69933. }
  69934. if (this.bloomEnabled) {
  69935. if (this._hdr) {
  69936. this.copyBack.shareOutputWith(this.blurX);
  69937. if (this.imageProcessing) {
  69938. this.imageProcessing.shareOutputWith(this.pass);
  69939. this.imageProcessing.autoClear = false;
  69940. }
  69941. else {
  69942. this.finalMerge.shareOutputWith(this.pass);
  69943. }
  69944. }
  69945. else {
  69946. this.finalMerge.shareOutputWith(this.pass);
  69947. }
  69948. }
  69949. if (this.fxaaEnabled) {
  69950. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  69951. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  69952. this._setAutoClearAndTextureSharing(this.fxaa);
  69953. }
  69954. if (this.chromaticAberrationEnabled) {
  69955. if (!this.chromaticAberration.isReady()) {
  69956. this.chromaticAberration.updateEffect();
  69957. }
  69958. this.addEffect(this._chromaticAberrationEffect);
  69959. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  69960. }
  69961. if (this._cameras !== null) {
  69962. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69963. }
  69964. if (this.msaaEnabled) {
  69965. if (!this._enableMSAAOnFirstPostProcess()) {
  69966. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  69967. }
  69968. }
  69969. };
  69970. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  69971. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  69972. for (var i = 0; i < this._cameras.length; i++) {
  69973. var camera = this._cameras[i];
  69974. if (this.pass) {
  69975. this.pass.dispose(camera);
  69976. }
  69977. if (this.highlights) {
  69978. this.highlights.dispose(camera);
  69979. }
  69980. if (this.blurX) {
  69981. this.blurX.dispose(camera);
  69982. }
  69983. if (this.blurY) {
  69984. this.blurY.dispose(camera);
  69985. }
  69986. if (this.copyBack) {
  69987. this.copyBack.dispose(camera);
  69988. }
  69989. if (this.imageProcessing) {
  69990. this.imageProcessing.dispose(camera);
  69991. }
  69992. if (this.fxaa) {
  69993. this.fxaa.dispose(camera);
  69994. }
  69995. if (this.finalMerge) {
  69996. this.finalMerge.dispose(camera);
  69997. }
  69998. // These are created in the constructor and should not be disposed on every pipeline change
  69999. if (disposeNonRecreated) {
  70000. if (this.sharpen) {
  70001. this.sharpen.dispose(camera);
  70002. }
  70003. if (this.depthOfField) {
  70004. this.depthOfField.disposeEffects(camera);
  70005. }
  70006. if (this.chromaticAberration) {
  70007. this.chromaticAberration.dispose(camera);
  70008. }
  70009. }
  70010. }
  70011. this.pass = null;
  70012. this.highlights = null;
  70013. this.blurX = null;
  70014. this.blurY = null;
  70015. this.copyBack = null;
  70016. this.imageProcessing = null;
  70017. this.fxaa = null;
  70018. this.finalMerge = null;
  70019. if (disposeNonRecreated) {
  70020. this.sharpen = null;
  70021. this.depthOfField = null;
  70022. this.chromaticAberration = null;
  70023. }
  70024. };
  70025. /**
  70026. * Dispose of the pipeline and stop all post processes
  70027. */
  70028. DefaultRenderingPipeline.prototype.dispose = function () {
  70029. this._disposePostProcesses(true);
  70030. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70031. _super.prototype.dispose.call(this);
  70032. };
  70033. /**
  70034. * Serialize the rendering pipeline (Used when exporting)
  70035. * @returns the serialized object
  70036. */
  70037. DefaultRenderingPipeline.prototype.serialize = function () {
  70038. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  70039. serializationObject.customType = "DefaultRenderingPipeline";
  70040. return serializationObject;
  70041. };
  70042. /**
  70043. * Parse the serialized pipeline
  70044. * @param source Source pipeline.
  70045. * @param scene The scene to load the pipeline to.
  70046. * @param rootUrl The URL of the serialized pipeline.
  70047. * @returns An instantiated pipeline from the serialized object.
  70048. */
  70049. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  70050. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  70051. };
  70052. __decorate([
  70053. BABYLON.serialize()
  70054. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  70055. __decorate([
  70056. BABYLON.serialize()
  70057. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  70058. __decorate([
  70059. BABYLON.serialize()
  70060. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  70061. __decorate([
  70062. BABYLON.serialize()
  70063. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  70064. __decorate([
  70065. BABYLON.serialize()
  70066. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  70067. __decorate([
  70068. BABYLON.serialize()
  70069. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  70070. __decorate([
  70071. BABYLON.serialize()
  70072. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  70073. __decorate([
  70074. BABYLON.serialize()
  70075. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  70076. __decorate([
  70077. BABYLON.serialize()
  70078. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  70079. __decorate([
  70080. BABYLON.serialize()
  70081. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  70082. __decorate([
  70083. BABYLON.serialize()
  70084. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  70085. __decorate([
  70086. BABYLON.serialize()
  70087. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  70088. __decorate([
  70089. BABYLON.serialize()
  70090. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  70091. return DefaultRenderingPipeline;
  70092. }(BABYLON.PostProcessRenderPipeline));
  70093. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  70094. })(BABYLON || (BABYLON = {}));
  70095. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  70096. "use strict";
  70097. var BABYLON;
  70098. (function (BABYLON) {
  70099. /**
  70100. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  70101. */
  70102. var GeometryBufferRenderer = /** @class */ (function () {
  70103. /**
  70104. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  70105. * @param scene The scene the buffer belongs to
  70106. * @param ratio How big is the buffer related to the main canvas.
  70107. */
  70108. function GeometryBufferRenderer(scene, ratio) {
  70109. if (ratio === void 0) { ratio = 1; }
  70110. this._enablePosition = false;
  70111. this._scene = scene;
  70112. this._ratio = ratio;
  70113. // Render target
  70114. this._createRenderTargets();
  70115. }
  70116. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  70117. /**
  70118. * Set the render list (meshes to be rendered) used in the G buffer.
  70119. */
  70120. set: function (meshes) {
  70121. this._multiRenderTarget.renderList = meshes;
  70122. },
  70123. enumerable: true,
  70124. configurable: true
  70125. });
  70126. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  70127. /**
  70128. * Gets wether or not G buffer are supported by the running hardware.
  70129. * This requires draw buffer supports
  70130. */
  70131. get: function () {
  70132. return this._multiRenderTarget.isSupported;
  70133. },
  70134. enumerable: true,
  70135. configurable: true
  70136. });
  70137. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  70138. /**
  70139. * Gets wether or not position are enabled for the G buffer.
  70140. */
  70141. get: function () {
  70142. return this._enablePosition;
  70143. },
  70144. /**
  70145. * Sets wether or not position are enabled for the G buffer.
  70146. */
  70147. set: function (enable) {
  70148. this._enablePosition = enable;
  70149. this.dispose();
  70150. this._createRenderTargets();
  70151. },
  70152. enumerable: true,
  70153. configurable: true
  70154. });
  70155. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  70156. /**
  70157. * Gets the scene associated with the buffer.
  70158. */
  70159. get: function () {
  70160. return this._scene;
  70161. },
  70162. enumerable: true,
  70163. configurable: true
  70164. });
  70165. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  70166. /**
  70167. * Gets the ratio used by the buffer during its creation.
  70168. * How big is the buffer related to the main canvas.
  70169. */
  70170. get: function () {
  70171. return this._ratio;
  70172. },
  70173. enumerable: true,
  70174. configurable: true
  70175. });
  70176. /**
  70177. * Checks wether everything is ready to render a submesh to the G buffer.
  70178. * @param subMesh the submesh to check readiness for
  70179. * @param useInstances is the mesh drawn using instance or not
  70180. * @returns true if ready otherwise false
  70181. */
  70182. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  70183. var material = subMesh.getMaterial();
  70184. if (material && material.disableDepthWrite) {
  70185. return false;
  70186. }
  70187. var defines = [];
  70188. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70189. var mesh = subMesh.getMesh();
  70190. // Alpha test
  70191. if (material && material.needAlphaTesting()) {
  70192. defines.push("#define ALPHATEST");
  70193. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70194. attribs.push(BABYLON.VertexBuffer.UVKind);
  70195. defines.push("#define UV1");
  70196. }
  70197. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70198. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70199. defines.push("#define UV2");
  70200. }
  70201. }
  70202. // Buffers
  70203. if (this._enablePosition) {
  70204. defines.push("#define POSITION");
  70205. }
  70206. // Bones
  70207. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70208. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70209. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70210. if (mesh.numBoneInfluencers > 4) {
  70211. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70212. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70213. }
  70214. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70215. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70216. }
  70217. else {
  70218. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70219. }
  70220. // Instances
  70221. if (useInstances) {
  70222. defines.push("#define INSTANCES");
  70223. attribs.push("world0");
  70224. attribs.push("world1");
  70225. attribs.push("world2");
  70226. attribs.push("world3");
  70227. }
  70228. // Get correct effect
  70229. var join = defines.join("\n");
  70230. if (this._cachedDefines !== join) {
  70231. this._cachedDefines = join;
  70232. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  70233. }
  70234. return this._effect.isReady();
  70235. };
  70236. /**
  70237. * Gets the current underlying G Buffer.
  70238. * @returns the buffer
  70239. */
  70240. GeometryBufferRenderer.prototype.getGBuffer = function () {
  70241. return this._multiRenderTarget;
  70242. };
  70243. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  70244. /**
  70245. * Gets the number of samples used to render the buffer (anti aliasing).
  70246. */
  70247. get: function () {
  70248. return this._multiRenderTarget.samples;
  70249. },
  70250. /**
  70251. * Sets the number of samples used to render the buffer (anti aliasing).
  70252. */
  70253. set: function (value) {
  70254. this._multiRenderTarget.samples = value;
  70255. },
  70256. enumerable: true,
  70257. configurable: true
  70258. });
  70259. /**
  70260. * Disposes the renderer and frees up associated resources.
  70261. */
  70262. GeometryBufferRenderer.prototype.dispose = function () {
  70263. this.getGBuffer().dispose();
  70264. };
  70265. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  70266. var _this = this;
  70267. var engine = this._scene.getEngine();
  70268. var count = this._enablePosition ? 3 : 2;
  70269. 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 });
  70270. if (!this.isSupported) {
  70271. return;
  70272. }
  70273. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70274. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70275. this._multiRenderTarget.refreshRate = 1;
  70276. this._multiRenderTarget.renderParticles = false;
  70277. this._multiRenderTarget.renderList = null;
  70278. // set default depth value to 1.0 (far away)
  70279. this._multiRenderTarget.onClearObservable.add(function (engine) {
  70280. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  70281. });
  70282. // Custom render function
  70283. var renderSubMesh = function (subMesh) {
  70284. var mesh = subMesh.getRenderingMesh();
  70285. var scene = _this._scene;
  70286. var engine = scene.getEngine();
  70287. var material = subMesh.getMaterial();
  70288. if (!material) {
  70289. return;
  70290. }
  70291. // Culling
  70292. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70293. // Managing instances
  70294. var batch = mesh._getInstancesRenderList(subMesh._id);
  70295. if (batch.mustReturn) {
  70296. return;
  70297. }
  70298. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70299. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  70300. engine.enableEffect(_this._effect);
  70301. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  70302. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  70303. _this._effect.setMatrix("view", scene.getViewMatrix());
  70304. // Alpha test
  70305. if (material && material.needAlphaTesting()) {
  70306. var alphaTexture = material.getAlphaTestTexture();
  70307. if (alphaTexture) {
  70308. _this._effect.setTexture("diffuseSampler", alphaTexture);
  70309. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70310. }
  70311. }
  70312. // Bones
  70313. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70314. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70315. }
  70316. // Draw
  70317. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  70318. }
  70319. };
  70320. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70321. var index;
  70322. if (depthOnlySubMeshes.length) {
  70323. engine.setColorWrite(false);
  70324. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70325. renderSubMesh(depthOnlySubMeshes.data[index]);
  70326. }
  70327. engine.setColorWrite(true);
  70328. }
  70329. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70330. renderSubMesh(opaqueSubMeshes.data[index]);
  70331. }
  70332. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70333. renderSubMesh(alphaTestSubMeshes.data[index]);
  70334. }
  70335. };
  70336. };
  70337. return GeometryBufferRenderer;
  70338. }());
  70339. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  70340. })(BABYLON || (BABYLON = {}));
  70341. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  70342. "use strict";
  70343. var BABYLON;
  70344. (function (BABYLON) {
  70345. var RefractionPostProcess = /** @class */ (function (_super) {
  70346. __extends(RefractionPostProcess, _super);
  70347. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  70348. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  70349. _this.color = color;
  70350. _this.depth = depth;
  70351. _this.colorLevel = colorLevel;
  70352. _this._ownRefractionTexture = true;
  70353. _this.onActivateObservable.add(function (cam) {
  70354. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  70355. });
  70356. _this.onApplyObservable.add(function (effect) {
  70357. effect.setColor3("baseColor", _this.color);
  70358. effect.setFloat("depth", _this.depth);
  70359. effect.setFloat("colorLevel", _this.colorLevel);
  70360. effect.setTexture("refractionSampler", _this._refTexture);
  70361. });
  70362. return _this;
  70363. }
  70364. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  70365. /**
  70366. * Gets or sets the refraction texture
  70367. * Please note that you are responsible for disposing the texture if you set it manually
  70368. */
  70369. get: function () {
  70370. return this._refTexture;
  70371. },
  70372. set: function (value) {
  70373. if (this._refTexture && this._ownRefractionTexture) {
  70374. this._refTexture.dispose();
  70375. }
  70376. this._refTexture = value;
  70377. this._ownRefractionTexture = false;
  70378. },
  70379. enumerable: true,
  70380. configurable: true
  70381. });
  70382. // Methods
  70383. RefractionPostProcess.prototype.dispose = function (camera) {
  70384. if (this._refTexture && this._ownRefractionTexture) {
  70385. this._refTexture.dispose();
  70386. this._refTexture = null;
  70387. }
  70388. _super.prototype.dispose.call(this, camera);
  70389. };
  70390. return RefractionPostProcess;
  70391. }(BABYLON.PostProcess));
  70392. BABYLON.RefractionPostProcess = RefractionPostProcess;
  70393. })(BABYLON || (BABYLON = {}));
  70394. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  70395. "use strict";
  70396. var BABYLON;
  70397. (function (BABYLON) {
  70398. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  70399. __extends(BlackAndWhitePostProcess, _super);
  70400. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  70401. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  70402. _this.degree = 1;
  70403. _this.onApplyObservable.add(function (effect) {
  70404. effect.setFloat("degree", _this.degree);
  70405. });
  70406. return _this;
  70407. }
  70408. return BlackAndWhitePostProcess;
  70409. }(BABYLON.PostProcess));
  70410. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  70411. })(BABYLON || (BABYLON = {}));
  70412. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  70413. "use strict";
  70414. var BABYLON;
  70415. (function (BABYLON) {
  70416. /**
  70417. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  70418. * input texture to perform effects such as edge detection or sharpening
  70419. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70420. */
  70421. var ConvolutionPostProcess = /** @class */ (function (_super) {
  70422. __extends(ConvolutionPostProcess, _super);
  70423. /**
  70424. * Creates a new instance of @see ConvolutionPostProcess
  70425. * @param name The name of the effect.
  70426. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  70427. * @param options The required width/height ratio to downsize to before computing the render pass.
  70428. * @param camera The camera to apply the render pass to.
  70429. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70430. * @param engine The engine which the post process will be applied. (default: current engine)
  70431. * @param reusable If the post process can be reused on the same frame. (default: false)
  70432. * @param textureType Type of textures used when performing the post process. (default: 0)
  70433. */
  70434. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  70435. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70436. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70437. _this.kernel = kernel;
  70438. _this.onApply = function (effect) {
  70439. effect.setFloat2("screenSize", _this.width, _this.height);
  70440. effect.setArray("kernel", _this.kernel);
  70441. };
  70442. return _this;
  70443. }
  70444. // Statics
  70445. /**
  70446. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70447. */
  70448. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  70449. /**
  70450. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70451. */
  70452. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  70453. /**
  70454. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70455. */
  70456. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  70457. /**
  70458. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70459. */
  70460. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  70461. /**
  70462. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70463. */
  70464. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  70465. /**
  70466. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  70467. */
  70468. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  70469. return ConvolutionPostProcess;
  70470. }(BABYLON.PostProcess));
  70471. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  70472. })(BABYLON || (BABYLON = {}));
  70473. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  70474. "use strict";
  70475. var BABYLON;
  70476. (function (BABYLON) {
  70477. var FilterPostProcess = /** @class */ (function (_super) {
  70478. __extends(FilterPostProcess, _super);
  70479. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  70480. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  70481. _this.kernelMatrix = kernelMatrix;
  70482. _this.onApply = function (effect) {
  70483. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  70484. };
  70485. return _this;
  70486. }
  70487. return FilterPostProcess;
  70488. }(BABYLON.PostProcess));
  70489. BABYLON.FilterPostProcess = FilterPostProcess;
  70490. })(BABYLON || (BABYLON = {}));
  70491. //# sourceMappingURL=babylon.filterPostProcess.js.map
  70492. "use strict";
  70493. var BABYLON;
  70494. (function (BABYLON) {
  70495. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  70496. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  70497. __extends(VolumetricLightScatteringPostProcess, _super);
  70498. /**
  70499. * @constructor
  70500. * @param {string} name - The post-process name
  70501. * @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)
  70502. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  70503. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  70504. * @param {number} samples - The post-process quality, default 100
  70505. * @param {number} samplingMode - The post-process filtering mode
  70506. * @param {BABYLON.Engine} engine - The babylon engine
  70507. * @param {boolean} reusable - If the post-process is reusable
  70508. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  70509. */
  70510. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  70511. if (samples === void 0) { samples = 100; }
  70512. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70513. 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;
  70514. _this._screenCoordinates = BABYLON.Vector2.Zero();
  70515. /**
  70516. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  70517. * @type {Vector3}
  70518. */
  70519. _this.customMeshPosition = BABYLON.Vector3.Zero();
  70520. /**
  70521. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  70522. * @type {boolean}
  70523. */
  70524. _this.useCustomMeshPosition = false;
  70525. /**
  70526. * If the post-process should inverse the light scattering direction
  70527. * @type {boolean}
  70528. */
  70529. _this.invert = true;
  70530. /**
  70531. * Array containing the excluded meshes not rendered in the internal pass
  70532. */
  70533. _this.excludedMeshes = new Array();
  70534. /**
  70535. * Controls the overall intensity of the post-process
  70536. * @type {number}
  70537. */
  70538. _this.exposure = 0.3;
  70539. /**
  70540. * Dissipates each sample's contribution in range [0, 1]
  70541. * @type {number}
  70542. */
  70543. _this.decay = 0.96815;
  70544. /**
  70545. * Controls the overall intensity of each sample
  70546. * @type {number}
  70547. */
  70548. _this.weight = 0.58767;
  70549. /**
  70550. * Controls the density of each sample
  70551. * @type {number}
  70552. */
  70553. _this.density = 0.926;
  70554. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  70555. engine = scene.getEngine();
  70556. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  70557. // Configure mesh
  70558. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  70559. // Configure
  70560. _this._createPass(scene, ratio.passRatio || ratio);
  70561. _this.onActivate = function (camera) {
  70562. if (!_this.isSupported) {
  70563. _this.dispose(camera);
  70564. }
  70565. _this.onActivate = null;
  70566. };
  70567. _this.onApplyObservable.add(function (effect) {
  70568. _this._updateMeshScreenCoordinates(scene);
  70569. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  70570. effect.setFloat("exposure", _this.exposure);
  70571. effect.setFloat("decay", _this.decay);
  70572. effect.setFloat("weight", _this.weight);
  70573. effect.setFloat("density", _this.density);
  70574. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  70575. });
  70576. return _this;
  70577. }
  70578. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  70579. get: function () {
  70580. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70581. return false;
  70582. },
  70583. set: function (useDiffuseColor) {
  70584. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  70585. },
  70586. enumerable: true,
  70587. configurable: true
  70588. });
  70589. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  70590. return "VolumetricLightScatteringPostProcess";
  70591. };
  70592. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  70593. var mesh = subMesh.getMesh();
  70594. // Render this.mesh as default
  70595. if (mesh === this.mesh && mesh.material) {
  70596. return mesh.material.isReady(mesh);
  70597. }
  70598. var defines = [];
  70599. var attribs = [BABYLON.VertexBuffer.PositionKind];
  70600. var material = subMesh.getMaterial();
  70601. // Alpha test
  70602. if (material) {
  70603. if (material.needAlphaTesting()) {
  70604. defines.push("#define ALPHATEST");
  70605. }
  70606. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70607. attribs.push(BABYLON.VertexBuffer.UVKind);
  70608. defines.push("#define UV1");
  70609. }
  70610. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70611. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70612. defines.push("#define UV2");
  70613. }
  70614. }
  70615. // Bones
  70616. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70617. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70618. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70619. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70620. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  70621. }
  70622. else {
  70623. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70624. }
  70625. // Instances
  70626. if (useInstances) {
  70627. defines.push("#define INSTANCES");
  70628. attribs.push("world0");
  70629. attribs.push("world1");
  70630. attribs.push("world2");
  70631. attribs.push("world3");
  70632. }
  70633. // Get correct effect
  70634. var join = defines.join("\n");
  70635. if (this._cachedDefines !== join) {
  70636. this._cachedDefines = join;
  70637. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  70638. }
  70639. return this._volumetricLightScatteringPass.isReady();
  70640. };
  70641. /**
  70642. * Sets the new light position for light scattering effect
  70643. * @param {BABYLON.Vector3} The new custom light position
  70644. */
  70645. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  70646. this.customMeshPosition = position;
  70647. };
  70648. /**
  70649. * Returns the light position for light scattering effect
  70650. * @return {BABYLON.Vector3} The custom light position
  70651. */
  70652. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  70653. return this.customMeshPosition;
  70654. };
  70655. /**
  70656. * Disposes the internal assets and detaches the post-process from the camera
  70657. */
  70658. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  70659. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  70660. if (rttIndex !== -1) {
  70661. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  70662. }
  70663. this._volumetricLightScatteringRTT.dispose();
  70664. _super.prototype.dispose.call(this, camera);
  70665. };
  70666. /**
  70667. * Returns the render target texture used by the post-process
  70668. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  70669. */
  70670. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  70671. return this._volumetricLightScatteringRTT;
  70672. };
  70673. // Private methods
  70674. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  70675. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  70676. return true;
  70677. }
  70678. return false;
  70679. };
  70680. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  70681. var _this = this;
  70682. var engine = scene.getEngine();
  70683. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  70684. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70685. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70686. this._volumetricLightScatteringRTT.renderList = null;
  70687. this._volumetricLightScatteringRTT.renderParticles = false;
  70688. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  70689. var camera = this.getCamera();
  70690. if (camera) {
  70691. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70692. }
  70693. else {
  70694. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  70695. }
  70696. // Custom render function for submeshes
  70697. var renderSubMesh = function (subMesh) {
  70698. var mesh = subMesh.getRenderingMesh();
  70699. if (_this._meshExcluded(mesh)) {
  70700. return;
  70701. }
  70702. var material = subMesh.getMaterial();
  70703. if (!material) {
  70704. return;
  70705. }
  70706. var scene = mesh.getScene();
  70707. var engine = scene.getEngine();
  70708. // Culling
  70709. engine.setState(material.backFaceCulling);
  70710. // Managing instances
  70711. var batch = mesh._getInstancesRenderList(subMesh._id);
  70712. if (batch.mustReturn) {
  70713. return;
  70714. }
  70715. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70716. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  70717. var effect = _this._volumetricLightScatteringPass;
  70718. if (mesh === _this.mesh) {
  70719. if (subMesh.effect) {
  70720. effect = subMesh.effect;
  70721. }
  70722. else {
  70723. effect = material.getEffect();
  70724. }
  70725. }
  70726. engine.enableEffect(effect);
  70727. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  70728. if (mesh === _this.mesh) {
  70729. material.bind(mesh.getWorldMatrix(), mesh);
  70730. }
  70731. else {
  70732. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  70733. // Alpha test
  70734. if (material && material.needAlphaTesting()) {
  70735. var alphaTexture = material.getAlphaTestTexture();
  70736. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  70737. if (alphaTexture) {
  70738. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  70739. }
  70740. }
  70741. // Bones
  70742. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  70743. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  70744. }
  70745. }
  70746. // Draw
  70747. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  70748. }
  70749. };
  70750. // Render target texture callbacks
  70751. var savedSceneClearColor;
  70752. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  70753. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  70754. savedSceneClearColor = scene.clearColor;
  70755. scene.clearColor = sceneClearColor;
  70756. });
  70757. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  70758. scene.clearColor = savedSceneClearColor;
  70759. });
  70760. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  70761. var engine = scene.getEngine();
  70762. var index;
  70763. if (depthOnlySubMeshes.length) {
  70764. engine.setColorWrite(false);
  70765. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  70766. renderSubMesh(depthOnlySubMeshes.data[index]);
  70767. }
  70768. engine.setColorWrite(true);
  70769. }
  70770. for (index = 0; index < opaqueSubMeshes.length; index++) {
  70771. renderSubMesh(opaqueSubMeshes.data[index]);
  70772. }
  70773. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  70774. renderSubMesh(alphaTestSubMeshes.data[index]);
  70775. }
  70776. if (transparentSubMeshes.length) {
  70777. // Sort sub meshes
  70778. for (index = 0; index < transparentSubMeshes.length; index++) {
  70779. var submesh = transparentSubMeshes.data[index];
  70780. var boundingInfo = submesh.getBoundingInfo();
  70781. if (boundingInfo && scene.activeCamera) {
  70782. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  70783. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  70784. }
  70785. }
  70786. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  70787. sortedArray.sort(function (a, b) {
  70788. // Alpha index first
  70789. if (a._alphaIndex > b._alphaIndex) {
  70790. return 1;
  70791. }
  70792. if (a._alphaIndex < b._alphaIndex) {
  70793. return -1;
  70794. }
  70795. // Then distance to camera
  70796. if (a._distanceToCamera < b._distanceToCamera) {
  70797. return 1;
  70798. }
  70799. if (a._distanceToCamera > b._distanceToCamera) {
  70800. return -1;
  70801. }
  70802. return 0;
  70803. });
  70804. // Render sub meshes
  70805. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  70806. for (index = 0; index < sortedArray.length; index++) {
  70807. renderSubMesh(sortedArray[index]);
  70808. }
  70809. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  70810. }
  70811. };
  70812. };
  70813. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  70814. var transform = scene.getTransformMatrix();
  70815. var meshPosition;
  70816. if (this.useCustomMeshPosition) {
  70817. meshPosition = this.customMeshPosition;
  70818. }
  70819. else if (this.attachedNode) {
  70820. meshPosition = this.attachedNode.position;
  70821. }
  70822. else {
  70823. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  70824. }
  70825. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  70826. this._screenCoordinates.x = pos.x / this._viewPort.width;
  70827. this._screenCoordinates.y = pos.y / this._viewPort.height;
  70828. if (this.invert)
  70829. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  70830. };
  70831. // Static methods
  70832. /**
  70833. * Creates a default mesh for the Volumeric Light Scattering post-process
  70834. * @param {string} The mesh name
  70835. * @param {BABYLON.Scene} The scene where to create the mesh
  70836. * @return {BABYLON.Mesh} the default mesh
  70837. */
  70838. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  70839. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  70840. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  70841. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  70842. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  70843. mesh.material = material;
  70844. return mesh;
  70845. };
  70846. __decorate([
  70847. BABYLON.serializeAsVector3()
  70848. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  70849. __decorate([
  70850. BABYLON.serialize()
  70851. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  70852. __decorate([
  70853. BABYLON.serialize()
  70854. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  70855. __decorate([
  70856. BABYLON.serializeAsMeshReference()
  70857. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  70858. __decorate([
  70859. BABYLON.serialize()
  70860. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  70861. __decorate([
  70862. BABYLON.serialize()
  70863. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  70864. __decorate([
  70865. BABYLON.serialize()
  70866. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  70867. __decorate([
  70868. BABYLON.serialize()
  70869. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  70870. __decorate([
  70871. BABYLON.serialize()
  70872. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  70873. return VolumetricLightScatteringPostProcess;
  70874. }(BABYLON.PostProcess));
  70875. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  70876. })(BABYLON || (BABYLON = {}));
  70877. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  70878. "use strict";
  70879. //
  70880. // This post-process allows the modification of rendered colors by using
  70881. // a 'look-up table' (LUT). This effect is also called Color Grading.
  70882. //
  70883. // The object needs to be provided an url to a texture containing the color
  70884. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  70885. // Use an image editing software to tweak the LUT to match your needs.
  70886. //
  70887. // For an example of a color LUT, see here:
  70888. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  70889. // For explanations on color grading, see here:
  70890. // http://udn.epicgames.com/Three/ColorGrading.html
  70891. //
  70892. var BABYLON;
  70893. (function (BABYLON) {
  70894. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  70895. __extends(ColorCorrectionPostProcess, _super);
  70896. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  70897. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  70898. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  70899. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  70900. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70901. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70902. _this.onApply = function (effect) {
  70903. effect.setTexture("colorTable", _this._colorTableTexture);
  70904. };
  70905. return _this;
  70906. }
  70907. return ColorCorrectionPostProcess;
  70908. }(BABYLON.PostProcess));
  70909. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  70910. })(BABYLON || (BABYLON = {}));
  70911. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  70912. "use strict";
  70913. var BABYLON;
  70914. (function (BABYLON) {
  70915. var TonemappingOperator;
  70916. (function (TonemappingOperator) {
  70917. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  70918. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  70919. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  70920. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  70921. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  70922. ;
  70923. var TonemapPostProcess = /** @class */ (function (_super) {
  70924. __extends(TonemapPostProcess, _super);
  70925. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  70926. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70927. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70928. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  70929. _this._operator = _operator;
  70930. _this.exposureAdjustment = exposureAdjustment;
  70931. var defines = "#define ";
  70932. if (_this._operator === TonemappingOperator.Hable)
  70933. defines += "HABLE_TONEMAPPING";
  70934. else if (_this._operator === TonemappingOperator.Reinhard)
  70935. defines += "REINHARD_TONEMAPPING";
  70936. else if (_this._operator === TonemappingOperator.HejiDawson)
  70937. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  70938. else if (_this._operator === TonemappingOperator.Photographic)
  70939. defines += "PHOTOGRAPHIC_TONEMAPPING";
  70940. //sadly a second call to create the effect.
  70941. _this.updateEffect(defines);
  70942. _this.onApply = function (effect) {
  70943. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  70944. };
  70945. return _this;
  70946. }
  70947. return TonemapPostProcess;
  70948. }(BABYLON.PostProcess));
  70949. BABYLON.TonemapPostProcess = TonemapPostProcess;
  70950. })(BABYLON || (BABYLON = {}));
  70951. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  70952. "use strict";
  70953. var BABYLON;
  70954. (function (BABYLON) {
  70955. var DisplayPassPostProcess = /** @class */ (function (_super) {
  70956. __extends(DisplayPassPostProcess, _super);
  70957. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  70958. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  70959. }
  70960. return DisplayPassPostProcess;
  70961. }(BABYLON.PostProcess));
  70962. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  70963. })(BABYLON || (BABYLON = {}));
  70964. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  70965. "use strict";
  70966. var BABYLON;
  70967. (function (BABYLON) {
  70968. var HighlightsPostProcess = /** @class */ (function (_super) {
  70969. __extends(HighlightsPostProcess, _super);
  70970. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70971. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70972. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  70973. }
  70974. return HighlightsPostProcess;
  70975. }(BABYLON.PostProcess));
  70976. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  70977. })(BABYLON || (BABYLON = {}));
  70978. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  70979. "use strict";
  70980. var BABYLON;
  70981. (function (BABYLON) {
  70982. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  70983. __extends(ImageProcessingPostProcess, _super);
  70984. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  70985. if (camera === void 0) { camera = null; }
  70986. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70987. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  70988. _this._fromLinearSpace = true;
  70989. /**
  70990. * Defines cache preventing GC.
  70991. */
  70992. _this._defines = {
  70993. IMAGEPROCESSING: false,
  70994. VIGNETTE: false,
  70995. VIGNETTEBLENDMODEMULTIPLY: false,
  70996. VIGNETTEBLENDMODEOPAQUE: false,
  70997. TONEMAPPING: false,
  70998. CONTRAST: false,
  70999. COLORCURVES: false,
  71000. COLORGRADING: false,
  71001. COLORGRADING3D: false,
  71002. FROMLINEARSPACE: false,
  71003. SAMPLER3DGREENDEPTH: false,
  71004. SAMPLER3DBGRMAP: false,
  71005. IMAGEPROCESSINGPOSTPROCESS: false,
  71006. EXPOSURE: false,
  71007. GRAIN: false,
  71008. };
  71009. // Setup the configuration as forced by the constructor. This would then not force the
  71010. // scene materials output in linear space and let untouched the default forward pass.
  71011. if (imageProcessingConfiguration) {
  71012. imageProcessingConfiguration.applyByPostProcess = true;
  71013. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  71014. // This will cause the shader to be compiled
  71015. _this.fromLinearSpace = false;
  71016. }
  71017. else {
  71018. _this._attachImageProcessingConfiguration(null, true);
  71019. _this.imageProcessingConfiguration.applyByPostProcess = true;
  71020. }
  71021. _this.onApply = function (effect) {
  71022. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  71023. };
  71024. return _this;
  71025. }
  71026. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  71027. /**
  71028. * Gets the image processing configuration used either in this material.
  71029. */
  71030. get: function () {
  71031. return this._imageProcessingConfiguration;
  71032. },
  71033. /**
  71034. * Sets the Default image processing configuration used either in the this material.
  71035. *
  71036. * If sets to null, the scene one is in use.
  71037. */
  71038. set: function (value) {
  71039. this._attachImageProcessingConfiguration(value);
  71040. },
  71041. enumerable: true,
  71042. configurable: true
  71043. });
  71044. /**
  71045. * Attaches a new image processing configuration to the PBR Material.
  71046. * @param configuration
  71047. */
  71048. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  71049. var _this = this;
  71050. if (doNotBuild === void 0) { doNotBuild = false; }
  71051. if (configuration === this._imageProcessingConfiguration) {
  71052. return;
  71053. }
  71054. // Detaches observer.
  71055. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71056. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71057. }
  71058. // Pick the scene configuration if needed.
  71059. if (!configuration) {
  71060. var scene = null;
  71061. var engine = this.getEngine();
  71062. var camera = this.getCamera();
  71063. if (camera) {
  71064. scene = camera.getScene();
  71065. }
  71066. else if (engine && engine.scenes) {
  71067. var scenes = engine.scenes;
  71068. scene = scenes[scenes.length - 1];
  71069. }
  71070. else {
  71071. scene = BABYLON.Engine.LastCreatedScene;
  71072. }
  71073. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  71074. }
  71075. else {
  71076. this._imageProcessingConfiguration = configuration;
  71077. }
  71078. // Attaches observer.
  71079. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  71080. _this._updateParameters();
  71081. });
  71082. // Ensure the effect will be rebuilt.
  71083. if (!doNotBuild) {
  71084. this._updateParameters();
  71085. }
  71086. };
  71087. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  71088. /**
  71089. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71090. */
  71091. get: function () {
  71092. return this.imageProcessingConfiguration.colorCurves;
  71093. },
  71094. /**
  71095. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71096. */
  71097. set: function (value) {
  71098. this.imageProcessingConfiguration.colorCurves = value;
  71099. },
  71100. enumerable: true,
  71101. configurable: true
  71102. });
  71103. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  71104. /**
  71105. * Gets wether the color curves effect is enabled.
  71106. */
  71107. get: function () {
  71108. return this.imageProcessingConfiguration.colorCurvesEnabled;
  71109. },
  71110. /**
  71111. * Sets wether the color curves effect is enabled.
  71112. */
  71113. set: function (value) {
  71114. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  71115. },
  71116. enumerable: true,
  71117. configurable: true
  71118. });
  71119. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  71120. /**
  71121. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71122. */
  71123. get: function () {
  71124. return this.imageProcessingConfiguration.colorGradingTexture;
  71125. },
  71126. /**
  71127. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71128. */
  71129. set: function (value) {
  71130. this.imageProcessingConfiguration.colorGradingTexture = value;
  71131. },
  71132. enumerable: true,
  71133. configurable: true
  71134. });
  71135. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  71136. /**
  71137. * Gets wether the color grading effect is enabled.
  71138. */
  71139. get: function () {
  71140. return this.imageProcessingConfiguration.colorGradingEnabled;
  71141. },
  71142. /**
  71143. * Gets wether the color grading effect is enabled.
  71144. */
  71145. set: function (value) {
  71146. this.imageProcessingConfiguration.colorGradingEnabled = value;
  71147. },
  71148. enumerable: true,
  71149. configurable: true
  71150. });
  71151. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  71152. /**
  71153. * Gets exposure used in the effect.
  71154. */
  71155. get: function () {
  71156. return this.imageProcessingConfiguration.exposure;
  71157. },
  71158. /**
  71159. * Sets exposure used in the effect.
  71160. */
  71161. set: function (value) {
  71162. this.imageProcessingConfiguration.exposure = value;
  71163. },
  71164. enumerable: true,
  71165. configurable: true
  71166. });
  71167. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  71168. /**
  71169. * Gets wether tonemapping is enabled or not.
  71170. */
  71171. get: function () {
  71172. return this._imageProcessingConfiguration.toneMappingEnabled;
  71173. },
  71174. /**
  71175. * Sets wether tonemapping is enabled or not
  71176. */
  71177. set: function (value) {
  71178. this._imageProcessingConfiguration.toneMappingEnabled = value;
  71179. },
  71180. enumerable: true,
  71181. configurable: true
  71182. });
  71183. ;
  71184. ;
  71185. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  71186. /**
  71187. * Gets contrast used in the effect.
  71188. */
  71189. get: function () {
  71190. return this.imageProcessingConfiguration.contrast;
  71191. },
  71192. /**
  71193. * Sets contrast used in the effect.
  71194. */
  71195. set: function (value) {
  71196. this.imageProcessingConfiguration.contrast = value;
  71197. },
  71198. enumerable: true,
  71199. configurable: true
  71200. });
  71201. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  71202. /**
  71203. * Gets Vignette stretch size.
  71204. */
  71205. get: function () {
  71206. return this.imageProcessingConfiguration.vignetteStretch;
  71207. },
  71208. /**
  71209. * Sets Vignette stretch size.
  71210. */
  71211. set: function (value) {
  71212. this.imageProcessingConfiguration.vignetteStretch = value;
  71213. },
  71214. enumerable: true,
  71215. configurable: true
  71216. });
  71217. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  71218. /**
  71219. * Gets Vignette centre X Offset.
  71220. */
  71221. get: function () {
  71222. return this.imageProcessingConfiguration.vignetteCentreX;
  71223. },
  71224. /**
  71225. * Sets Vignette centre X Offset.
  71226. */
  71227. set: function (value) {
  71228. this.imageProcessingConfiguration.vignetteCentreX = value;
  71229. },
  71230. enumerable: true,
  71231. configurable: true
  71232. });
  71233. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  71234. /**
  71235. * Gets Vignette centre Y Offset.
  71236. */
  71237. get: function () {
  71238. return this.imageProcessingConfiguration.vignetteCentreY;
  71239. },
  71240. /**
  71241. * Sets Vignette centre Y Offset.
  71242. */
  71243. set: function (value) {
  71244. this.imageProcessingConfiguration.vignetteCentreY = value;
  71245. },
  71246. enumerable: true,
  71247. configurable: true
  71248. });
  71249. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  71250. /**
  71251. * Gets Vignette weight or intensity of the vignette effect.
  71252. */
  71253. get: function () {
  71254. return this.imageProcessingConfiguration.vignetteWeight;
  71255. },
  71256. /**
  71257. * Sets Vignette weight or intensity of the vignette effect.
  71258. */
  71259. set: function (value) {
  71260. this.imageProcessingConfiguration.vignetteWeight = value;
  71261. },
  71262. enumerable: true,
  71263. configurable: true
  71264. });
  71265. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  71266. /**
  71267. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71268. * if vignetteEnabled is set to true.
  71269. */
  71270. get: function () {
  71271. return this.imageProcessingConfiguration.vignetteColor;
  71272. },
  71273. /**
  71274. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71275. * if vignetteEnabled is set to true.
  71276. */
  71277. set: function (value) {
  71278. this.imageProcessingConfiguration.vignetteColor = value;
  71279. },
  71280. enumerable: true,
  71281. configurable: true
  71282. });
  71283. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  71284. /**
  71285. * Gets Camera field of view used by the Vignette effect.
  71286. */
  71287. get: function () {
  71288. return this.imageProcessingConfiguration.vignetteCameraFov;
  71289. },
  71290. /**
  71291. * Sets Camera field of view used by the Vignette effect.
  71292. */
  71293. set: function (value) {
  71294. this.imageProcessingConfiguration.vignetteCameraFov = value;
  71295. },
  71296. enumerable: true,
  71297. configurable: true
  71298. });
  71299. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  71300. /**
  71301. * Gets the vignette blend mode allowing different kind of effect.
  71302. */
  71303. get: function () {
  71304. return this.imageProcessingConfiguration.vignetteBlendMode;
  71305. },
  71306. /**
  71307. * Sets the vignette blend mode allowing different kind of effect.
  71308. */
  71309. set: function (value) {
  71310. this.imageProcessingConfiguration.vignetteBlendMode = value;
  71311. },
  71312. enumerable: true,
  71313. configurable: true
  71314. });
  71315. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  71316. /**
  71317. * Gets wether the vignette effect is enabled.
  71318. */
  71319. get: function () {
  71320. return this.imageProcessingConfiguration.vignetteEnabled;
  71321. },
  71322. /**
  71323. * Sets wether the vignette effect is enabled.
  71324. */
  71325. set: function (value) {
  71326. this.imageProcessingConfiguration.vignetteEnabled = value;
  71327. },
  71328. enumerable: true,
  71329. configurable: true
  71330. });
  71331. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  71332. /**
  71333. * Gets wether the grain effect is enabled.
  71334. */
  71335. get: function () {
  71336. return this.imageProcessingConfiguration.grainEnabled;
  71337. },
  71338. /**
  71339. * Sets wether the grain effect is enabled.
  71340. */
  71341. set: function (value) {
  71342. this.imageProcessingConfiguration.grainEnabled = value;
  71343. },
  71344. enumerable: true,
  71345. configurable: true
  71346. });
  71347. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  71348. /**
  71349. * Gets the grain effect's intensity.
  71350. */
  71351. get: function () {
  71352. return this.imageProcessingConfiguration.grainIntensity;
  71353. },
  71354. /**
  71355. * Sets the grain effect's intensity.
  71356. */
  71357. set: function (value) {
  71358. this.imageProcessingConfiguration.grainIntensity = value;
  71359. },
  71360. enumerable: true,
  71361. configurable: true
  71362. });
  71363. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  71364. /**
  71365. * Gets wether the grain effect is animated.
  71366. */
  71367. get: function () {
  71368. return this.imageProcessingConfiguration.grainAnimated;
  71369. },
  71370. /**
  71371. * Sets wether the grain effect is animated.
  71372. */
  71373. set: function (value) {
  71374. this.imageProcessingConfiguration.grainAnimated = value;
  71375. },
  71376. enumerable: true,
  71377. configurable: true
  71378. });
  71379. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  71380. /**
  71381. * Gets wether the input of the processing is in Gamma or Linear Space.
  71382. */
  71383. get: function () {
  71384. return this._fromLinearSpace;
  71385. },
  71386. /**
  71387. * Sets wether the input of the processing is in Gamma or Linear Space.
  71388. */
  71389. set: function (value) {
  71390. if (this._fromLinearSpace === value) {
  71391. return;
  71392. }
  71393. this._fromLinearSpace = value;
  71394. this._updateParameters();
  71395. },
  71396. enumerable: true,
  71397. configurable: true
  71398. });
  71399. ImageProcessingPostProcess.prototype.getClassName = function () {
  71400. return "ImageProcessingPostProcess";
  71401. };
  71402. ImageProcessingPostProcess.prototype._updateParameters = function () {
  71403. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  71404. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  71405. var defines = "";
  71406. for (var define in this._defines) {
  71407. if (this._defines[define]) {
  71408. defines += "#define " + define + ";\r\n";
  71409. }
  71410. }
  71411. var samplers = ["textureSampler"];
  71412. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  71413. var uniforms = ["scale"];
  71414. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  71415. this.updateEffect(defines, uniforms, samplers);
  71416. };
  71417. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  71418. _super.prototype.dispose.call(this, camera);
  71419. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71420. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71421. }
  71422. this.imageProcessingConfiguration.applyByPostProcess = false;
  71423. };
  71424. __decorate([
  71425. BABYLON.serialize()
  71426. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  71427. return ImageProcessingPostProcess;
  71428. }(BABYLON.PostProcess));
  71429. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  71430. })(BABYLON || (BABYLON = {}));
  71431. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  71432. "use strict";
  71433. var BABYLON;
  71434. (function (BABYLON) {
  71435. var Bone = /** @class */ (function (_super) {
  71436. __extends(Bone, _super);
  71437. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  71438. if (parentBone === void 0) { parentBone = null; }
  71439. if (localMatrix === void 0) { localMatrix = null; }
  71440. if (restPose === void 0) { restPose = null; }
  71441. if (baseMatrix === void 0) { baseMatrix = null; }
  71442. if (index === void 0) { index = null; }
  71443. var _this = _super.call(this, name, skeleton.getScene()) || this;
  71444. _this.name = name;
  71445. _this.children = new Array();
  71446. _this.animations = new Array();
  71447. // Set this value to map this bone to a different index in the transform matrices.
  71448. // Set this value to -1 to exclude the bone from the transform matrices.
  71449. _this._index = null;
  71450. _this._worldTransform = new BABYLON.Matrix();
  71451. _this._absoluteTransform = new BABYLON.Matrix();
  71452. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  71453. _this._scaleMatrix = BABYLON.Matrix.Identity();
  71454. _this._scaleVector = BABYLON.Vector3.One();
  71455. _this._negateScaleChildren = BABYLON.Vector3.One();
  71456. _this._scalingDeterminant = 1;
  71457. _this._skeleton = skeleton;
  71458. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  71459. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  71460. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  71461. _this._index = index;
  71462. skeleton.bones.push(_this);
  71463. _this.setParent(parentBone, false);
  71464. _this._updateDifferenceMatrix();
  71465. return _this;
  71466. }
  71467. Object.defineProperty(Bone.prototype, "_matrix", {
  71468. get: function () {
  71469. return this._localMatrix;
  71470. },
  71471. set: function (val) {
  71472. if (this._localMatrix) {
  71473. this._localMatrix.copyFrom(val);
  71474. }
  71475. else {
  71476. this._localMatrix = val;
  71477. }
  71478. },
  71479. enumerable: true,
  71480. configurable: true
  71481. });
  71482. // Members
  71483. Bone.prototype.getSkeleton = function () {
  71484. return this._skeleton;
  71485. };
  71486. Bone.prototype.getParent = function () {
  71487. return this._parent;
  71488. };
  71489. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  71490. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71491. if (this._parent === parent) {
  71492. return;
  71493. }
  71494. if (this._parent) {
  71495. var index = this._parent.children.indexOf(this);
  71496. if (index !== -1) {
  71497. this._parent.children.splice(index, 1);
  71498. }
  71499. }
  71500. this._parent = parent;
  71501. if (this._parent) {
  71502. this._parent.children.push(this);
  71503. }
  71504. if (updateDifferenceMatrix) {
  71505. this._updateDifferenceMatrix();
  71506. }
  71507. };
  71508. Bone.prototype.getLocalMatrix = function () {
  71509. return this._localMatrix;
  71510. };
  71511. Bone.prototype.getBaseMatrix = function () {
  71512. return this._baseMatrix;
  71513. };
  71514. Bone.prototype.getRestPose = function () {
  71515. return this._restPose;
  71516. };
  71517. Bone.prototype.returnToRest = function () {
  71518. this.updateMatrix(this._restPose.clone());
  71519. };
  71520. Bone.prototype.getWorldMatrix = function () {
  71521. return this._worldTransform;
  71522. };
  71523. Bone.prototype.getInvertedAbsoluteTransform = function () {
  71524. return this._invertedAbsoluteTransform;
  71525. };
  71526. Bone.prototype.getAbsoluteTransform = function () {
  71527. return this._absoluteTransform;
  71528. };
  71529. Object.defineProperty(Bone.prototype, "position", {
  71530. // Properties (matches AbstractMesh properties)
  71531. get: function () {
  71532. return this.getPosition();
  71533. },
  71534. set: function (newPosition) {
  71535. this.setPosition(newPosition);
  71536. },
  71537. enumerable: true,
  71538. configurable: true
  71539. });
  71540. Object.defineProperty(Bone.prototype, "rotation", {
  71541. get: function () {
  71542. return this.getRotation();
  71543. },
  71544. set: function (newRotation) {
  71545. this.setRotation(newRotation);
  71546. },
  71547. enumerable: true,
  71548. configurable: true
  71549. });
  71550. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  71551. get: function () {
  71552. return this.getRotationQuaternion();
  71553. },
  71554. set: function (newRotation) {
  71555. this.setRotationQuaternion(newRotation);
  71556. },
  71557. enumerable: true,
  71558. configurable: true
  71559. });
  71560. Object.defineProperty(Bone.prototype, "scaling", {
  71561. get: function () {
  71562. return this.getScale();
  71563. },
  71564. set: function (newScaling) {
  71565. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  71566. },
  71567. enumerable: true,
  71568. configurable: true
  71569. });
  71570. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  71571. /**
  71572. * Gets the animation properties override
  71573. */
  71574. get: function () {
  71575. return this._skeleton.animationPropertiesOverride;
  71576. },
  71577. enumerable: true,
  71578. configurable: true
  71579. });
  71580. // Methods
  71581. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  71582. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  71583. this._baseMatrix = matrix.clone();
  71584. this._localMatrix = matrix.clone();
  71585. this._skeleton._markAsDirty();
  71586. if (updateDifferenceMatrix) {
  71587. this._updateDifferenceMatrix();
  71588. }
  71589. };
  71590. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  71591. if (!rootMatrix) {
  71592. rootMatrix = this._baseMatrix;
  71593. }
  71594. if (this._parent) {
  71595. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  71596. }
  71597. else {
  71598. this._absoluteTransform.copyFrom(rootMatrix);
  71599. }
  71600. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  71601. for (var index = 0; index < this.children.length; index++) {
  71602. this.children[index]._updateDifferenceMatrix();
  71603. }
  71604. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  71605. };
  71606. Bone.prototype.markAsDirty = function () {
  71607. this._currentRenderId++;
  71608. this._skeleton._markAsDirty();
  71609. };
  71610. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  71611. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71612. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  71613. // all animation may be coming from a library skeleton, so may need to create animation
  71614. if (this.animations.length === 0) {
  71615. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  71616. this.animations[0].setKeys([]);
  71617. }
  71618. // get animation info / verify there is such a range from the source bone
  71619. var sourceRange = source.animations[0].getRange(rangeName);
  71620. if (!sourceRange) {
  71621. return false;
  71622. }
  71623. var from = sourceRange.from;
  71624. var to = sourceRange.to;
  71625. var sourceKeys = source.animations[0].getKeys();
  71626. // rescaling prep
  71627. var sourceBoneLength = source.length;
  71628. var sourceParent = source.getParent();
  71629. var parent = this.getParent();
  71630. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  71631. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  71632. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  71633. var destKeys = this.animations[0].getKeys();
  71634. // loop vars declaration
  71635. var orig;
  71636. var origTranslation;
  71637. var mat;
  71638. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  71639. orig = sourceKeys[key];
  71640. if (orig.frame >= from && orig.frame <= to) {
  71641. if (rescaleAsRequired) {
  71642. mat = orig.value.clone();
  71643. // scale based on parent ratio, when bone has parent
  71644. if (parentScalingReqd) {
  71645. origTranslation = mat.getTranslation();
  71646. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  71647. // scale based on skeleton dimension ratio when root bone, and value is passed
  71648. }
  71649. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  71650. origTranslation = mat.getTranslation();
  71651. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  71652. // use original when root bone, and no data for skelDimensionsRatio
  71653. }
  71654. else {
  71655. mat = orig.value;
  71656. }
  71657. }
  71658. else {
  71659. mat = orig.value;
  71660. }
  71661. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  71662. }
  71663. }
  71664. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  71665. return true;
  71666. };
  71667. /**
  71668. * Translate the bone in local or world space.
  71669. * @param vec The amount to translate the bone.
  71670. * @param space The space that the translation is in.
  71671. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71672. */
  71673. Bone.prototype.translate = function (vec, space, mesh) {
  71674. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71675. var lm = this.getLocalMatrix();
  71676. if (space == BABYLON.Space.LOCAL) {
  71677. lm.m[12] += vec.x;
  71678. lm.m[13] += vec.y;
  71679. lm.m[14] += vec.z;
  71680. }
  71681. else {
  71682. var wm = null;
  71683. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71684. if (mesh) {
  71685. wm = mesh.getWorldMatrix();
  71686. }
  71687. this._skeleton.computeAbsoluteTransforms();
  71688. var tmat = Bone._tmpMats[0];
  71689. var tvec = Bone._tmpVecs[0];
  71690. if (this._parent) {
  71691. if (mesh && wm) {
  71692. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71693. tmat.multiplyToRef(wm, tmat);
  71694. }
  71695. else {
  71696. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71697. }
  71698. }
  71699. tmat.m[12] = 0;
  71700. tmat.m[13] = 0;
  71701. tmat.m[14] = 0;
  71702. tmat.invert();
  71703. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  71704. lm.m[12] += tvec.x;
  71705. lm.m[13] += tvec.y;
  71706. lm.m[14] += tvec.z;
  71707. }
  71708. this.markAsDirty();
  71709. };
  71710. /**
  71711. * Set the postion of the bone in local or world space.
  71712. * @param position The position to set the bone.
  71713. * @param space The space that the position is in.
  71714. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71715. */
  71716. Bone.prototype.setPosition = function (position, space, mesh) {
  71717. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71718. var lm = this.getLocalMatrix();
  71719. if (space == BABYLON.Space.LOCAL) {
  71720. lm.m[12] = position.x;
  71721. lm.m[13] = position.y;
  71722. lm.m[14] = position.z;
  71723. }
  71724. else {
  71725. var wm = null;
  71726. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  71727. if (mesh) {
  71728. wm = mesh.getWorldMatrix();
  71729. }
  71730. this._skeleton.computeAbsoluteTransforms();
  71731. var tmat = Bone._tmpMats[0];
  71732. var vec = Bone._tmpVecs[0];
  71733. if (this._parent) {
  71734. if (mesh && wm) {
  71735. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71736. tmat.multiplyToRef(wm, tmat);
  71737. }
  71738. else {
  71739. tmat.copyFrom(this._parent.getAbsoluteTransform());
  71740. }
  71741. }
  71742. tmat.invert();
  71743. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  71744. lm.m[12] = vec.x;
  71745. lm.m[13] = vec.y;
  71746. lm.m[14] = vec.z;
  71747. }
  71748. this.markAsDirty();
  71749. };
  71750. /**
  71751. * Set the absolute postion of the bone (world space).
  71752. * @param position The position to set the bone.
  71753. * @param mesh The mesh that this bone is attached to.
  71754. */
  71755. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  71756. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  71757. };
  71758. /**
  71759. * Set the scale of the bone on the x, y and z axes.
  71760. * @param x The scale of the bone on the x axis.
  71761. * @param x The scale of the bone on the y axis.
  71762. * @param z The scale of the bone on the z axis.
  71763. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71764. */
  71765. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  71766. if (scaleChildren === void 0) { scaleChildren = false; }
  71767. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  71768. if (!scaleChildren) {
  71769. this._negateScaleChildren.x = 1 / x;
  71770. this._negateScaleChildren.y = 1 / y;
  71771. this._negateScaleChildren.z = 1 / z;
  71772. }
  71773. this._syncScaleVector();
  71774. }
  71775. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  71776. };
  71777. /**
  71778. * Scale the bone on the x, y and z axes.
  71779. * @param x The amount to scale the bone on the x axis.
  71780. * @param x The amount to scale the bone on the y axis.
  71781. * @param z The amount to scale the bone on the z axis.
  71782. * @param scaleChildren Set this to true if children of the bone should be scaled.
  71783. */
  71784. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  71785. if (scaleChildren === void 0) { scaleChildren = false; }
  71786. var locMat = this.getLocalMatrix();
  71787. var origLocMat = Bone._tmpMats[0];
  71788. origLocMat.copyFrom(locMat);
  71789. var origLocMatInv = Bone._tmpMats[1];
  71790. origLocMatInv.copyFrom(origLocMat);
  71791. origLocMatInv.invert();
  71792. var scaleMat = Bone._tmpMats[2];
  71793. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  71794. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  71795. this._scaleVector.x *= x;
  71796. this._scaleVector.y *= y;
  71797. this._scaleVector.z *= z;
  71798. locMat.multiplyToRef(origLocMatInv, locMat);
  71799. locMat.multiplyToRef(scaleMat, locMat);
  71800. locMat.multiplyToRef(origLocMat, locMat);
  71801. var parent = this.getParent();
  71802. if (parent) {
  71803. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  71804. }
  71805. else {
  71806. this.getAbsoluteTransform().copyFrom(locMat);
  71807. }
  71808. var len = this.children.length;
  71809. scaleMat.invert();
  71810. for (var i = 0; i < len; i++) {
  71811. var child = this.children[i];
  71812. var cm = child.getLocalMatrix();
  71813. cm.multiplyToRef(scaleMat, cm);
  71814. var lm = child.getLocalMatrix();
  71815. lm.m[12] *= x;
  71816. lm.m[13] *= y;
  71817. lm.m[14] *= z;
  71818. }
  71819. this.computeAbsoluteTransforms();
  71820. if (scaleChildren) {
  71821. for (var i = 0; i < len; i++) {
  71822. this.children[i].scale(x, y, z, scaleChildren);
  71823. }
  71824. }
  71825. this.markAsDirty();
  71826. };
  71827. /**
  71828. * Set the yaw, pitch, and roll of the bone in local or world space.
  71829. * @param yaw The rotation of the bone on the y axis.
  71830. * @param pitch The rotation of the bone on the x axis.
  71831. * @param roll The rotation of the bone on the z axis.
  71832. * @param space The space that the axes of rotation are in.
  71833. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71834. */
  71835. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  71836. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71837. var rotMat = Bone._tmpMats[0];
  71838. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  71839. var rotMatInv = Bone._tmpMats[1];
  71840. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71841. rotMatInv.multiplyToRef(rotMat, rotMat);
  71842. this._rotateWithMatrix(rotMat, space, mesh);
  71843. };
  71844. /**
  71845. * Rotate the bone on an axis in local or world space.
  71846. * @param axis The axis to rotate the bone on.
  71847. * @param amount The amount to rotate the bone.
  71848. * @param space The space that the axis is in.
  71849. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71850. */
  71851. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  71852. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71853. var rmat = Bone._tmpMats[0];
  71854. rmat.m[12] = 0;
  71855. rmat.m[13] = 0;
  71856. rmat.m[14] = 0;
  71857. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  71858. this._rotateWithMatrix(rmat, space, mesh);
  71859. };
  71860. /**
  71861. * Set the rotation of the bone to a particular axis angle in local or world space.
  71862. * @param axis The axis to rotate the bone on.
  71863. * @param angle The angle that the bone should be rotated to.
  71864. * @param space The space that the axis is in.
  71865. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71866. */
  71867. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  71868. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71869. var rotMat = Bone._tmpMats[0];
  71870. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  71871. var rotMatInv = Bone._tmpMats[1];
  71872. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71873. rotMatInv.multiplyToRef(rotMat, rotMat);
  71874. this._rotateWithMatrix(rotMat, space, mesh);
  71875. };
  71876. /**
  71877. * Set the euler rotation of the bone in local of world space.
  71878. * @param rotation The euler rotation that the bone should be set to.
  71879. * @param space The space that the rotation is in.
  71880. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71881. */
  71882. Bone.prototype.setRotation = function (rotation, space, mesh) {
  71883. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71884. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  71885. };
  71886. /**
  71887. * Set the quaternion rotation of the bone in local of world space.
  71888. * @param quat The quaternion rotation that the bone should be set to.
  71889. * @param space The space that the rotation is in.
  71890. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71891. */
  71892. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  71893. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71894. var rotMatInv = Bone._tmpMats[0];
  71895. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71896. var rotMat = Bone._tmpMats[1];
  71897. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  71898. rotMatInv.multiplyToRef(rotMat, rotMat);
  71899. this._rotateWithMatrix(rotMat, space, mesh);
  71900. };
  71901. /**
  71902. * Set the rotation matrix of the bone in local of world space.
  71903. * @param rotMat The rotation matrix that the bone should be set to.
  71904. * @param space The space that the rotation is in.
  71905. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  71906. */
  71907. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  71908. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71909. var rotMatInv = Bone._tmpMats[0];
  71910. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  71911. var rotMat2 = Bone._tmpMats[1];
  71912. rotMat2.copyFrom(rotMat);
  71913. rotMatInv.multiplyToRef(rotMat, rotMat2);
  71914. this._rotateWithMatrix(rotMat2, space, mesh);
  71915. };
  71916. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  71917. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71918. var lmat = this.getLocalMatrix();
  71919. var lx = lmat.m[12];
  71920. var ly = lmat.m[13];
  71921. var lz = lmat.m[14];
  71922. var parent = this.getParent();
  71923. var parentScale = Bone._tmpMats[3];
  71924. var parentScaleInv = Bone._tmpMats[4];
  71925. if (parent) {
  71926. if (space == BABYLON.Space.WORLD) {
  71927. if (mesh) {
  71928. parentScale.copyFrom(mesh.getWorldMatrix());
  71929. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  71930. }
  71931. else {
  71932. parentScale.copyFrom(parent.getAbsoluteTransform());
  71933. }
  71934. }
  71935. else {
  71936. parentScale = parent._scaleMatrix;
  71937. }
  71938. parentScaleInv.copyFrom(parentScale);
  71939. parentScaleInv.invert();
  71940. lmat.multiplyToRef(parentScale, lmat);
  71941. lmat.multiplyToRef(rmat, lmat);
  71942. lmat.multiplyToRef(parentScaleInv, lmat);
  71943. }
  71944. else {
  71945. if (space == BABYLON.Space.WORLD && mesh) {
  71946. parentScale.copyFrom(mesh.getWorldMatrix());
  71947. parentScaleInv.copyFrom(parentScale);
  71948. parentScaleInv.invert();
  71949. lmat.multiplyToRef(parentScale, lmat);
  71950. lmat.multiplyToRef(rmat, lmat);
  71951. lmat.multiplyToRef(parentScaleInv, lmat);
  71952. }
  71953. else {
  71954. lmat.multiplyToRef(rmat, lmat);
  71955. }
  71956. }
  71957. lmat.m[12] = lx;
  71958. lmat.m[13] = ly;
  71959. lmat.m[14] = lz;
  71960. this.computeAbsoluteTransforms();
  71961. this.markAsDirty();
  71962. };
  71963. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  71964. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  71965. if (space == BABYLON.Space.WORLD) {
  71966. var scaleMatrix = Bone._tmpMats[2];
  71967. scaleMatrix.copyFrom(this._scaleMatrix);
  71968. rotMatInv.copyFrom(this.getAbsoluteTransform());
  71969. if (mesh) {
  71970. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  71971. var meshScale = Bone._tmpMats[3];
  71972. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  71973. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  71974. }
  71975. rotMatInv.invert();
  71976. scaleMatrix.m[0] *= this._scalingDeterminant;
  71977. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71978. }
  71979. else {
  71980. rotMatInv.copyFrom(this.getLocalMatrix());
  71981. rotMatInv.invert();
  71982. var scaleMatrix = Bone._tmpMats[2];
  71983. scaleMatrix.copyFrom(this._scaleMatrix);
  71984. if (this._parent) {
  71985. var pscaleMatrix = Bone._tmpMats[3];
  71986. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  71987. pscaleMatrix.invert();
  71988. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  71989. }
  71990. else {
  71991. scaleMatrix.m[0] *= this._scalingDeterminant;
  71992. }
  71993. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  71994. }
  71995. };
  71996. /**
  71997. * Get the scale of the bone
  71998. * @returns the scale of the bone
  71999. */
  72000. Bone.prototype.getScale = function () {
  72001. return this._scaleVector.clone();
  72002. };
  72003. /**
  72004. * Copy the scale of the bone to a vector3.
  72005. * @param result The vector3 to copy the scale to
  72006. */
  72007. Bone.prototype.getScaleToRef = function (result) {
  72008. result.copyFrom(this._scaleVector);
  72009. };
  72010. /**
  72011. * Get the position of the bone in local or world space.
  72012. * @param space The space that the returned position is in.
  72013. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72014. * @returns The position of the bone
  72015. */
  72016. Bone.prototype.getPosition = function (space, mesh) {
  72017. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72018. if (mesh === void 0) { mesh = null; }
  72019. var pos = BABYLON.Vector3.Zero();
  72020. this.getPositionToRef(space, mesh, pos);
  72021. return pos;
  72022. };
  72023. /**
  72024. * Copy the position of the bone to a vector3 in local or world space.
  72025. * @param space The space that the returned position is in.
  72026. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72027. * @param result The vector3 to copy the position to.
  72028. */
  72029. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  72030. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72031. if (space == BABYLON.Space.LOCAL) {
  72032. var lm = this.getLocalMatrix();
  72033. result.x = lm.m[12];
  72034. result.y = lm.m[13];
  72035. result.z = lm.m[14];
  72036. }
  72037. else {
  72038. var wm = null;
  72039. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72040. if (mesh) {
  72041. wm = mesh.getWorldMatrix();
  72042. }
  72043. this._skeleton.computeAbsoluteTransforms();
  72044. var tmat = Bone._tmpMats[0];
  72045. if (mesh && wm) {
  72046. tmat.copyFrom(this.getAbsoluteTransform());
  72047. tmat.multiplyToRef(wm, tmat);
  72048. }
  72049. else {
  72050. tmat = this.getAbsoluteTransform();
  72051. }
  72052. result.x = tmat.m[12];
  72053. result.y = tmat.m[13];
  72054. result.z = tmat.m[14];
  72055. }
  72056. };
  72057. /**
  72058. * Get the absolute position of the bone (world space).
  72059. * @param mesh The mesh that this bone is attached to.
  72060. * @returns The absolute position of the bone
  72061. */
  72062. Bone.prototype.getAbsolutePosition = function (mesh) {
  72063. if (mesh === void 0) { mesh = null; }
  72064. var pos = BABYLON.Vector3.Zero();
  72065. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  72066. return pos;
  72067. };
  72068. /**
  72069. * Copy the absolute position of the bone (world space) to the result param.
  72070. * @param mesh The mesh that this bone is attached to.
  72071. * @param result The vector3 to copy the absolute position to.
  72072. */
  72073. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  72074. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  72075. };
  72076. /**
  72077. * Compute the absolute transforms of this bone and its children.
  72078. */
  72079. Bone.prototype.computeAbsoluteTransforms = function () {
  72080. if (this._parent) {
  72081. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72082. }
  72083. else {
  72084. this._absoluteTransform.copyFrom(this._localMatrix);
  72085. var poseMatrix = this._skeleton.getPoseMatrix();
  72086. if (poseMatrix) {
  72087. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  72088. }
  72089. }
  72090. var children = this.children;
  72091. var len = children.length;
  72092. for (var i = 0; i < len; i++) {
  72093. children[i].computeAbsoluteTransforms();
  72094. }
  72095. };
  72096. Bone.prototype._syncScaleVector = function () {
  72097. var lm = this.getLocalMatrix();
  72098. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  72099. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  72100. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  72101. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  72102. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  72103. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  72104. this._scaleVector.x = xs * Math.sqrt(xsq);
  72105. this._scaleVector.y = ys * Math.sqrt(ysq);
  72106. this._scaleVector.z = zs * Math.sqrt(zsq);
  72107. if (this._parent) {
  72108. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  72109. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  72110. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  72111. }
  72112. 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);
  72113. };
  72114. /**
  72115. * Get the world direction from an axis that is in the local space of the bone.
  72116. * @param localAxis The local direction that is used to compute the world direction.
  72117. * @param mesh The mesh that this bone is attached to.
  72118. * @returns The world direction
  72119. */
  72120. Bone.prototype.getDirection = function (localAxis, mesh) {
  72121. if (mesh === void 0) { mesh = null; }
  72122. var result = BABYLON.Vector3.Zero();
  72123. this.getDirectionToRef(localAxis, mesh, result);
  72124. return result;
  72125. };
  72126. /**
  72127. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  72128. * @param localAxis The local direction that is used to compute the world direction.
  72129. * @param mesh The mesh that this bone is attached to.
  72130. * @param result The vector3 that the world direction will be copied to.
  72131. */
  72132. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  72133. if (mesh === void 0) { mesh = null; }
  72134. var wm = null;
  72135. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72136. if (mesh) {
  72137. wm = mesh.getWorldMatrix();
  72138. }
  72139. this._skeleton.computeAbsoluteTransforms();
  72140. var mat = Bone._tmpMats[0];
  72141. mat.copyFrom(this.getAbsoluteTransform());
  72142. if (mesh && wm) {
  72143. mat.multiplyToRef(wm, mat);
  72144. }
  72145. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  72146. result.normalize();
  72147. };
  72148. /**
  72149. * Get the euler rotation of the bone in local or world space.
  72150. * @param space The space that the rotation should be in.
  72151. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72152. * @returns The euler rotation
  72153. */
  72154. Bone.prototype.getRotation = function (space, mesh) {
  72155. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72156. if (mesh === void 0) { mesh = null; }
  72157. var result = BABYLON.Vector3.Zero();
  72158. this.getRotationToRef(space, mesh, result);
  72159. return result;
  72160. };
  72161. /**
  72162. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  72163. * @param space The space that the rotation should be in.
  72164. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72165. * @param result The vector3 that the rotation should be copied to.
  72166. */
  72167. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  72168. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72169. if (mesh === void 0) { mesh = null; }
  72170. var quat = Bone._tmpQuat;
  72171. this.getRotationQuaternionToRef(space, mesh, quat);
  72172. quat.toEulerAnglesToRef(result);
  72173. };
  72174. /**
  72175. * Get the quaternion rotation of the bone in either local or world space.
  72176. * @param space The space that the rotation should be in.
  72177. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72178. * @returns The quaternion rotation
  72179. */
  72180. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  72181. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72182. if (mesh === void 0) { mesh = null; }
  72183. var result = BABYLON.Quaternion.Identity();
  72184. this.getRotationQuaternionToRef(space, mesh, result);
  72185. return result;
  72186. };
  72187. /**
  72188. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  72189. * @param space The space that the rotation should be in.
  72190. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72191. * @param result The quaternion that the rotation should be copied to.
  72192. */
  72193. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  72194. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72195. if (mesh === void 0) { mesh = null; }
  72196. if (space == BABYLON.Space.LOCAL) {
  72197. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72198. }
  72199. else {
  72200. var mat = Bone._tmpMats[0];
  72201. var amat = this.getAbsoluteTransform();
  72202. if (mesh) {
  72203. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72204. }
  72205. else {
  72206. mat.copyFrom(amat);
  72207. }
  72208. mat.m[0] *= this._scalingDeterminant;
  72209. mat.m[1] *= this._scalingDeterminant;
  72210. mat.m[2] *= this._scalingDeterminant;
  72211. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72212. }
  72213. };
  72214. /**
  72215. * Get the rotation matrix of the bone in local or world space.
  72216. * @param space The space that the rotation should be in.
  72217. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72218. * @returns The rotation matrix
  72219. */
  72220. Bone.prototype.getRotationMatrix = function (space, mesh) {
  72221. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72222. var result = BABYLON.Matrix.Identity();
  72223. this.getRotationMatrixToRef(space, mesh, result);
  72224. return result;
  72225. };
  72226. /**
  72227. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  72228. * @param space The space that the rotation should be in.
  72229. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72230. * @param result The quaternion that the rotation should be copied to.
  72231. */
  72232. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  72233. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72234. if (space == BABYLON.Space.LOCAL) {
  72235. this.getLocalMatrix().getRotationMatrixToRef(result);
  72236. }
  72237. else {
  72238. var mat = Bone._tmpMats[0];
  72239. var amat = this.getAbsoluteTransform();
  72240. if (mesh) {
  72241. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72242. }
  72243. else {
  72244. mat.copyFrom(amat);
  72245. }
  72246. mat.m[0] *= this._scalingDeterminant;
  72247. mat.m[1] *= this._scalingDeterminant;
  72248. mat.m[2] *= this._scalingDeterminant;
  72249. mat.getRotationMatrixToRef(result);
  72250. }
  72251. };
  72252. /**
  72253. * Get the world position of a point that is in the local space of the bone.
  72254. * @param position The local position
  72255. * @param mesh The mesh that this bone is attached to.
  72256. * @returns The world position
  72257. */
  72258. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  72259. if (mesh === void 0) { mesh = null; }
  72260. var result = BABYLON.Vector3.Zero();
  72261. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  72262. return result;
  72263. };
  72264. /**
  72265. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  72266. * @param position The local position
  72267. * @param mesh The mesh that this bone is attached to.
  72268. * @param result The vector3 that the world position should be copied to.
  72269. */
  72270. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  72271. if (mesh === void 0) { mesh = null; }
  72272. var wm = null;
  72273. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72274. if (mesh) {
  72275. wm = mesh.getWorldMatrix();
  72276. }
  72277. this._skeleton.computeAbsoluteTransforms();
  72278. var tmat = Bone._tmpMats[0];
  72279. if (mesh && wm) {
  72280. tmat.copyFrom(this.getAbsoluteTransform());
  72281. tmat.multiplyToRef(wm, tmat);
  72282. }
  72283. else {
  72284. tmat = this.getAbsoluteTransform();
  72285. }
  72286. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72287. };
  72288. /**
  72289. * Get the local position of a point that is in world space.
  72290. * @param position The world position
  72291. * @param mesh The mesh that this bone is attached to.
  72292. * @returns The local position
  72293. */
  72294. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  72295. if (mesh === void 0) { mesh = null; }
  72296. var result = BABYLON.Vector3.Zero();
  72297. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  72298. return result;
  72299. };
  72300. /**
  72301. * Get the local position of a point that is in world space and copy it to the result param.
  72302. * @param position The world position
  72303. * @param mesh The mesh that this bone is attached to.
  72304. * @param result The vector3 that the local position should be copied to.
  72305. */
  72306. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  72307. if (mesh === void 0) { mesh = null; }
  72308. var wm = null;
  72309. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72310. if (mesh) {
  72311. wm = mesh.getWorldMatrix();
  72312. }
  72313. this._skeleton.computeAbsoluteTransforms();
  72314. var tmat = Bone._tmpMats[0];
  72315. tmat.copyFrom(this.getAbsoluteTransform());
  72316. if (mesh && wm) {
  72317. tmat.multiplyToRef(wm, tmat);
  72318. }
  72319. tmat.invert();
  72320. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72321. };
  72322. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72323. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  72324. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72325. return Bone;
  72326. }(BABYLON.Node));
  72327. BABYLON.Bone = Bone;
  72328. })(BABYLON || (BABYLON = {}));
  72329. //# sourceMappingURL=babylon.bone.js.map
  72330. "use strict";
  72331. var BABYLON;
  72332. (function (BABYLON) {
  72333. var BoneIKController = /** @class */ (function () {
  72334. function BoneIKController(mesh, bone, options) {
  72335. this.targetPosition = BABYLON.Vector3.Zero();
  72336. this.poleTargetPosition = BABYLON.Vector3.Zero();
  72337. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  72338. this.poleAngle = 0;
  72339. this.slerpAmount = 1;
  72340. this._bone1Quat = BABYLON.Quaternion.Identity();
  72341. this._bone1Mat = BABYLON.Matrix.Identity();
  72342. this._bone2Ang = Math.PI;
  72343. this._maxAngle = Math.PI;
  72344. this._rightHandedSystem = false;
  72345. this._bendAxis = BABYLON.Vector3.Right();
  72346. this._slerping = false;
  72347. this._adjustRoll = 0;
  72348. this._bone2 = bone;
  72349. this._bone1 = bone.getParent();
  72350. if (!this._bone1) {
  72351. return;
  72352. }
  72353. this.mesh = mesh;
  72354. var bonePos = bone.getPosition();
  72355. if (bone.getAbsoluteTransform().determinant() > 0) {
  72356. this._rightHandedSystem = true;
  72357. this._bendAxis.x = 0;
  72358. this._bendAxis.y = 0;
  72359. this._bendAxis.z = -1;
  72360. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  72361. this._adjustRoll = Math.PI * .5;
  72362. this._bendAxis.z = 1;
  72363. }
  72364. }
  72365. if (this._bone1.length) {
  72366. var boneScale1 = this._bone1.getScale();
  72367. var boneScale2 = this._bone2.getScale();
  72368. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  72369. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  72370. }
  72371. else if (this._bone1.children[0]) {
  72372. mesh.computeWorldMatrix(true);
  72373. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  72374. var pos2 = this._bone2.getAbsolutePosition(mesh);
  72375. var pos3 = this._bone1.getAbsolutePosition(mesh);
  72376. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  72377. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  72378. }
  72379. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  72380. this.maxAngle = Math.PI;
  72381. if (options) {
  72382. if (options.targetMesh) {
  72383. this.targetMesh = options.targetMesh;
  72384. this.targetMesh.computeWorldMatrix(true);
  72385. }
  72386. if (options.poleTargetMesh) {
  72387. this.poleTargetMesh = options.poleTargetMesh;
  72388. this.poleTargetMesh.computeWorldMatrix(true);
  72389. }
  72390. else if (options.poleTargetBone) {
  72391. this.poleTargetBone = options.poleTargetBone;
  72392. }
  72393. else if (this._bone1.getParent()) {
  72394. this.poleTargetBone = this._bone1.getParent();
  72395. }
  72396. if (options.poleTargetLocalOffset) {
  72397. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  72398. }
  72399. if (options.poleAngle) {
  72400. this.poleAngle = options.poleAngle;
  72401. }
  72402. if (options.bendAxis) {
  72403. this._bendAxis.copyFrom(options.bendAxis);
  72404. }
  72405. if (options.maxAngle) {
  72406. this.maxAngle = options.maxAngle;
  72407. }
  72408. if (options.slerpAmount) {
  72409. this.slerpAmount = options.slerpAmount;
  72410. }
  72411. }
  72412. }
  72413. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  72414. get: function () {
  72415. return this._maxAngle;
  72416. },
  72417. set: function (value) {
  72418. this._setMaxAngle(value);
  72419. },
  72420. enumerable: true,
  72421. configurable: true
  72422. });
  72423. BoneIKController.prototype._setMaxAngle = function (ang) {
  72424. if (ang < 0) {
  72425. ang = 0;
  72426. }
  72427. if (ang > Math.PI || ang == undefined) {
  72428. ang = Math.PI;
  72429. }
  72430. this._maxAngle = ang;
  72431. var a = this._bone1Length;
  72432. var b = this._bone2Length;
  72433. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  72434. };
  72435. BoneIKController.prototype.update = function () {
  72436. var bone1 = this._bone1;
  72437. if (!bone1) {
  72438. return;
  72439. }
  72440. var target = this.targetPosition;
  72441. var poleTarget = this.poleTargetPosition;
  72442. var mat1 = BoneIKController._tmpMats[0];
  72443. var mat2 = BoneIKController._tmpMats[1];
  72444. if (this.targetMesh) {
  72445. target.copyFrom(this.targetMesh.getAbsolutePosition());
  72446. }
  72447. if (this.poleTargetBone) {
  72448. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  72449. }
  72450. else if (this.poleTargetMesh) {
  72451. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  72452. }
  72453. var bonePos = BoneIKController._tmpVecs[0];
  72454. var zaxis = BoneIKController._tmpVecs[1];
  72455. var xaxis = BoneIKController._tmpVecs[2];
  72456. var yaxis = BoneIKController._tmpVecs[3];
  72457. var upAxis = BoneIKController._tmpVecs[4];
  72458. var _tmpQuat = BoneIKController._tmpQuat;
  72459. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  72460. poleTarget.subtractToRef(bonePos, upAxis);
  72461. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  72462. upAxis.y = 1;
  72463. }
  72464. else {
  72465. upAxis.normalize();
  72466. }
  72467. target.subtractToRef(bonePos, yaxis);
  72468. yaxis.normalize();
  72469. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  72470. zaxis.normalize();
  72471. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  72472. xaxis.normalize();
  72473. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  72474. var a = this._bone1Length;
  72475. var b = this._bone2Length;
  72476. var c = BABYLON.Vector3.Distance(bonePos, target);
  72477. if (this._maxReach > 0) {
  72478. c = Math.min(this._maxReach, c);
  72479. }
  72480. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  72481. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  72482. if (acosa > 1) {
  72483. acosa = 1;
  72484. }
  72485. if (acosb > 1) {
  72486. acosb = 1;
  72487. }
  72488. if (acosa < -1) {
  72489. acosa = -1;
  72490. }
  72491. if (acosb < -1) {
  72492. acosb = -1;
  72493. }
  72494. var angA = Math.acos(acosa);
  72495. var angB = Math.acos(acosb);
  72496. var angC = -angA - angB;
  72497. if (this._rightHandedSystem) {
  72498. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  72499. mat2.multiplyToRef(mat1, mat1);
  72500. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  72501. mat2.multiplyToRef(mat1, mat1);
  72502. }
  72503. else {
  72504. var _tmpVec = BoneIKController._tmpVecs[5];
  72505. _tmpVec.copyFrom(this._bendAxis);
  72506. _tmpVec.x *= -1;
  72507. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  72508. mat2.multiplyToRef(mat1, mat1);
  72509. }
  72510. if (this.poleAngle) {
  72511. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  72512. mat1.multiplyToRef(mat2, mat1);
  72513. }
  72514. if (this._bone1) {
  72515. if (this.slerpAmount < 1) {
  72516. if (!this._slerping) {
  72517. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  72518. }
  72519. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  72520. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  72521. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  72522. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  72523. this._slerping = true;
  72524. }
  72525. else {
  72526. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  72527. this._bone1Mat.copyFrom(mat1);
  72528. this._slerping = false;
  72529. }
  72530. }
  72531. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  72532. this._bone2Ang = angC;
  72533. };
  72534. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72535. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  72536. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72537. return BoneIKController;
  72538. }());
  72539. BABYLON.BoneIKController = BoneIKController;
  72540. })(BABYLON || (BABYLON = {}));
  72541. //# sourceMappingURL=babylon.boneIKController.js.map
  72542. "use strict";
  72543. var BABYLON;
  72544. (function (BABYLON) {
  72545. var BoneLookController = /** @class */ (function () {
  72546. /**
  72547. * Create a BoneLookController
  72548. * @param mesh the mesh that the bone belongs to
  72549. * @param bone the bone that will be looking to the target
  72550. * @param target the target Vector3 to look at
  72551. * @param settings optional settings:
  72552. * - maxYaw: the maximum angle the bone will yaw to
  72553. * - minYaw: the minimum angle the bone will yaw to
  72554. * - maxPitch: the maximum angle the bone will pitch to
  72555. * - minPitch: the minimum angle the bone will yaw to
  72556. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  72557. * - upAxis: the up axis of the coordinate system
  72558. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72559. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  72560. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  72561. * - adjustYaw: used to make an adjustment to the yaw of the bone
  72562. * - adjustPitch: used to make an adjustment to the pitch of the bone
  72563. * - adjustRoll: used to make an adjustment to the roll of the bone
  72564. **/
  72565. function BoneLookController(mesh, bone, target, options) {
  72566. /**
  72567. * The up axis of the coordinate system that is used when the bone is rotated.
  72568. */
  72569. this.upAxis = BABYLON.Vector3.Up();
  72570. /**
  72571. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  72572. */
  72573. this.upAxisSpace = BABYLON.Space.LOCAL;
  72574. /**
  72575. * Used to make an adjustment to the yaw of the bone.
  72576. */
  72577. this.adjustYaw = 0;
  72578. /**
  72579. * Used to make an adjustment to the pitch of the bone.
  72580. */
  72581. this.adjustPitch = 0;
  72582. /**
  72583. * Used to make an adjustment to the roll of the bone.
  72584. */
  72585. this.adjustRoll = 0;
  72586. /**
  72587. * 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).
  72588. */
  72589. this.slerpAmount = 1;
  72590. this._boneQuat = BABYLON.Quaternion.Identity();
  72591. this._slerping = false;
  72592. this._firstFrameSkipped = false;
  72593. this._fowardAxis = BABYLON.Vector3.Forward();
  72594. this.mesh = mesh;
  72595. this.bone = bone;
  72596. this.target = target;
  72597. if (options) {
  72598. if (options.adjustYaw) {
  72599. this.adjustYaw = options.adjustYaw;
  72600. }
  72601. if (options.adjustPitch) {
  72602. this.adjustPitch = options.adjustPitch;
  72603. }
  72604. if (options.adjustRoll) {
  72605. this.adjustRoll = options.adjustRoll;
  72606. }
  72607. if (options.maxYaw != null) {
  72608. this.maxYaw = options.maxYaw;
  72609. }
  72610. else {
  72611. this.maxYaw = Math.PI;
  72612. }
  72613. if (options.minYaw != null) {
  72614. this.minYaw = options.minYaw;
  72615. }
  72616. else {
  72617. this.minYaw = -Math.PI;
  72618. }
  72619. if (options.maxPitch != null) {
  72620. this.maxPitch = options.maxPitch;
  72621. }
  72622. else {
  72623. this.maxPitch = Math.PI;
  72624. }
  72625. if (options.minPitch != null) {
  72626. this.minPitch = options.minPitch;
  72627. }
  72628. else {
  72629. this.minPitch = -Math.PI;
  72630. }
  72631. if (options.slerpAmount != null) {
  72632. this.slerpAmount = options.slerpAmount;
  72633. }
  72634. if (options.upAxis != null) {
  72635. this.upAxis = options.upAxis;
  72636. }
  72637. if (options.upAxisSpace != null) {
  72638. this.upAxisSpace = options.upAxisSpace;
  72639. }
  72640. if (options.yawAxis != null || options.pitchAxis != null) {
  72641. var newYawAxis = BABYLON.Axis.Y;
  72642. var newPitchAxis = BABYLON.Axis.X;
  72643. if (options.yawAxis != null) {
  72644. newYawAxis = options.yawAxis.clone();
  72645. newYawAxis.normalize();
  72646. }
  72647. if (options.pitchAxis != null) {
  72648. newPitchAxis = options.pitchAxis.clone();
  72649. newPitchAxis.normalize();
  72650. }
  72651. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  72652. this._transformYawPitch = BABYLON.Matrix.Identity();
  72653. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  72654. this._transformYawPitchInv = this._transformYawPitch.clone();
  72655. this._transformYawPitch.invert();
  72656. }
  72657. }
  72658. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  72659. this.upAxisSpace = BABYLON.Space.LOCAL;
  72660. }
  72661. }
  72662. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  72663. /**
  72664. * Get/set the minimum yaw angle that the bone can look to.
  72665. */
  72666. get: function () {
  72667. return this._minYaw;
  72668. },
  72669. set: function (value) {
  72670. this._minYaw = value;
  72671. this._minYawSin = Math.sin(value);
  72672. this._minYawCos = Math.cos(value);
  72673. if (this._maxYaw != null) {
  72674. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72675. this._yawRange = this._maxYaw - this._minYaw;
  72676. }
  72677. },
  72678. enumerable: true,
  72679. configurable: true
  72680. });
  72681. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  72682. /**
  72683. * Get/set the maximum yaw angle that the bone can look to.
  72684. */
  72685. get: function () {
  72686. return this._maxYaw;
  72687. },
  72688. set: function (value) {
  72689. this._maxYaw = value;
  72690. this._maxYawSin = Math.sin(value);
  72691. this._maxYawCos = Math.cos(value);
  72692. if (this._minYaw != null) {
  72693. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  72694. this._yawRange = this._maxYaw - this._minYaw;
  72695. }
  72696. },
  72697. enumerable: true,
  72698. configurable: true
  72699. });
  72700. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  72701. /**
  72702. * Get/set the minimum pitch angle that the bone can look to.
  72703. */
  72704. get: function () {
  72705. return this._minPitch;
  72706. },
  72707. set: function (value) {
  72708. this._minPitch = value;
  72709. this._minPitchTan = Math.tan(value);
  72710. },
  72711. enumerable: true,
  72712. configurable: true
  72713. });
  72714. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  72715. /**
  72716. * Get/set the maximum pitch angle that the bone can look to.
  72717. */
  72718. get: function () {
  72719. return this._maxPitch;
  72720. },
  72721. set: function (value) {
  72722. this._maxPitch = value;
  72723. this._maxPitchTan = Math.tan(value);
  72724. },
  72725. enumerable: true,
  72726. configurable: true
  72727. });
  72728. /**
  72729. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  72730. */
  72731. BoneLookController.prototype.update = function () {
  72732. //skip the first frame when slerping so that the mesh rotation is correct
  72733. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  72734. this._firstFrameSkipped = true;
  72735. return;
  72736. }
  72737. var bone = this.bone;
  72738. var bonePos = BoneLookController._tmpVecs[0];
  72739. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  72740. var target = this.target;
  72741. var _tmpMat1 = BoneLookController._tmpMats[0];
  72742. var _tmpMat2 = BoneLookController._tmpMats[1];
  72743. var mesh = this.mesh;
  72744. var parentBone = bone.getParent();
  72745. var upAxis = BoneLookController._tmpVecs[1];
  72746. upAxis.copyFrom(this.upAxis);
  72747. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  72748. if (this._transformYawPitch) {
  72749. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  72750. }
  72751. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  72752. }
  72753. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  72754. mesh.getDirectionToRef(upAxis, upAxis);
  72755. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  72756. upAxis.normalize();
  72757. }
  72758. }
  72759. var checkYaw = false;
  72760. var checkPitch = false;
  72761. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  72762. checkYaw = true;
  72763. }
  72764. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  72765. checkPitch = true;
  72766. }
  72767. if (checkYaw || checkPitch) {
  72768. var spaceMat = BoneLookController._tmpMats[2];
  72769. var spaceMatInv = BoneLookController._tmpMats[3];
  72770. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  72771. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  72772. }
  72773. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  72774. spaceMat.copyFrom(mesh.getWorldMatrix());
  72775. }
  72776. else {
  72777. var forwardAxis = BoneLookController._tmpVecs[2];
  72778. forwardAxis.copyFrom(this._fowardAxis);
  72779. if (this._transformYawPitch) {
  72780. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  72781. }
  72782. if (parentBone) {
  72783. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  72784. }
  72785. else {
  72786. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  72787. }
  72788. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  72789. rightAxis.normalize();
  72790. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  72791. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  72792. }
  72793. spaceMat.invertToRef(spaceMatInv);
  72794. var xzlen = null;
  72795. if (checkPitch) {
  72796. var localTarget = BoneLookController._tmpVecs[3];
  72797. target.subtractToRef(bonePos, localTarget);
  72798. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72799. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72800. var pitch = Math.atan2(localTarget.y, xzlen);
  72801. var newPitch = pitch;
  72802. if (pitch > this._maxPitch) {
  72803. localTarget.y = this._maxPitchTan * xzlen;
  72804. newPitch = this._maxPitch;
  72805. }
  72806. else if (pitch < this._minPitch) {
  72807. localTarget.y = this._minPitchTan * xzlen;
  72808. newPitch = this._minPitch;
  72809. }
  72810. if (pitch != newPitch) {
  72811. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72812. localTarget.addInPlace(bonePos);
  72813. target = localTarget;
  72814. }
  72815. }
  72816. if (checkYaw) {
  72817. var localTarget = BoneLookController._tmpVecs[4];
  72818. target.subtractToRef(bonePos, localTarget);
  72819. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  72820. var yaw = Math.atan2(localTarget.x, localTarget.z);
  72821. var newYaw = yaw;
  72822. if (yaw > this._maxYaw || yaw < this._minYaw) {
  72823. if (xzlen == null) {
  72824. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72825. }
  72826. if (this._yawRange > Math.PI) {
  72827. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  72828. localTarget.z = this._maxYawCos * xzlen;
  72829. localTarget.x = this._maxYawSin * xzlen;
  72830. newYaw = this._maxYaw;
  72831. }
  72832. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  72833. localTarget.z = this._minYawCos * xzlen;
  72834. localTarget.x = this._minYawSin * xzlen;
  72835. newYaw = this._minYaw;
  72836. }
  72837. }
  72838. else {
  72839. if (yaw > this._maxYaw) {
  72840. localTarget.z = this._maxYawCos * xzlen;
  72841. localTarget.x = this._maxYawSin * xzlen;
  72842. newYaw = this._maxYaw;
  72843. }
  72844. else if (yaw < this._minYaw) {
  72845. localTarget.z = this._minYawCos * xzlen;
  72846. localTarget.x = this._minYawSin * xzlen;
  72847. newYaw = this._minYaw;
  72848. }
  72849. }
  72850. }
  72851. if (this._slerping && this._yawRange > Math.PI) {
  72852. //are we going to be crossing into the min/max region?
  72853. var boneFwd = BoneLookController._tmpVecs[8];
  72854. boneFwd.copyFrom(BABYLON.Axis.Z);
  72855. if (this._transformYawPitch) {
  72856. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  72857. }
  72858. var boneRotMat = BoneLookController._tmpMats[4];
  72859. this._boneQuat.toRotationMatrix(boneRotMat);
  72860. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  72861. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  72862. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  72863. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  72864. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  72865. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  72866. if (angBtwTar > angBtwMidYaw) {
  72867. if (xzlen == null) {
  72868. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  72869. }
  72870. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  72871. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  72872. if (angBtwMin < angBtwMax) {
  72873. newYaw = boneYaw + Math.PI * .75;
  72874. localTarget.z = Math.cos(newYaw) * xzlen;
  72875. localTarget.x = Math.sin(newYaw) * xzlen;
  72876. }
  72877. else {
  72878. newYaw = boneYaw - Math.PI * .75;
  72879. localTarget.z = Math.cos(newYaw) * xzlen;
  72880. localTarget.x = Math.sin(newYaw) * xzlen;
  72881. }
  72882. }
  72883. }
  72884. if (yaw != newYaw) {
  72885. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  72886. localTarget.addInPlace(bonePos);
  72887. target = localTarget;
  72888. }
  72889. }
  72890. }
  72891. var zaxis = BoneLookController._tmpVecs[5];
  72892. var xaxis = BoneLookController._tmpVecs[6];
  72893. var yaxis = BoneLookController._tmpVecs[7];
  72894. var _tmpQuat = BoneLookController._tmpQuat;
  72895. target.subtractToRef(bonePos, zaxis);
  72896. zaxis.normalize();
  72897. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  72898. xaxis.normalize();
  72899. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  72900. yaxis.normalize();
  72901. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  72902. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  72903. return;
  72904. }
  72905. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  72906. return;
  72907. }
  72908. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  72909. return;
  72910. }
  72911. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  72912. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  72913. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  72914. }
  72915. if (this.slerpAmount < 1) {
  72916. if (!this._slerping) {
  72917. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  72918. }
  72919. if (this._transformYawPitch) {
  72920. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72921. }
  72922. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  72923. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  72924. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  72925. this._slerping = true;
  72926. }
  72927. else {
  72928. if (this._transformYawPitch) {
  72929. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  72930. }
  72931. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  72932. this._slerping = false;
  72933. }
  72934. };
  72935. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  72936. var angDiff = ang2 - ang1;
  72937. angDiff %= Math.PI * 2;
  72938. if (angDiff > Math.PI) {
  72939. angDiff -= Math.PI * 2;
  72940. }
  72941. else if (angDiff < -Math.PI) {
  72942. angDiff += Math.PI * 2;
  72943. }
  72944. return angDiff;
  72945. };
  72946. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  72947. ang1 %= (2 * Math.PI);
  72948. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72949. ang2 %= (2 * Math.PI);
  72950. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72951. var ab = 0;
  72952. if (ang1 < ang2) {
  72953. ab = ang2 - ang1;
  72954. }
  72955. else {
  72956. ab = ang1 - ang2;
  72957. }
  72958. if (ab > Math.PI) {
  72959. ab = Math.PI * 2 - ab;
  72960. }
  72961. return ab;
  72962. };
  72963. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  72964. ang %= (2 * Math.PI);
  72965. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  72966. ang1 %= (2 * Math.PI);
  72967. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  72968. ang2 %= (2 * Math.PI);
  72969. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  72970. if (ang1 < ang2) {
  72971. if (ang > ang1 && ang < ang2) {
  72972. return true;
  72973. }
  72974. }
  72975. else {
  72976. if (ang > ang2 && ang < ang1) {
  72977. return true;
  72978. }
  72979. }
  72980. return false;
  72981. };
  72982. 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()];
  72983. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  72984. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  72985. return BoneLookController;
  72986. }());
  72987. BABYLON.BoneLookController = BoneLookController;
  72988. })(BABYLON || (BABYLON = {}));
  72989. //# sourceMappingURL=babylon.boneLookController.js.map
  72990. "use strict";
  72991. var BABYLON;
  72992. (function (BABYLON) {
  72993. var Skeleton = /** @class */ (function () {
  72994. function Skeleton(name, id, scene) {
  72995. this.name = name;
  72996. this.id = id;
  72997. this.bones = new Array();
  72998. this.needInitialSkinMatrix = false;
  72999. this._isDirty = true;
  73000. this._meshesWithPoseMatrix = new Array();
  73001. this._identity = BABYLON.Matrix.Identity();
  73002. this._ranges = {};
  73003. this._lastAbsoluteTransformsUpdateId = -1;
  73004. /**
  73005. * Specifies if the skeleton should be serialized.
  73006. */
  73007. this.doNotSerialize = false;
  73008. // Events
  73009. /**
  73010. * An event triggered before computing the skeleton's matrices
  73011. * @type {BABYLON.Observable}
  73012. */
  73013. this.onBeforeComputeObservable = new BABYLON.Observable();
  73014. this.bones = [];
  73015. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73016. scene.skeletons.push(this);
  73017. //make sure it will recalculate the matrix next time prepare is called.
  73018. this._isDirty = true;
  73019. }
  73020. // Members
  73021. Skeleton.prototype.getTransformMatrices = function (mesh) {
  73022. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  73023. return mesh._bonesTransformMatrices;
  73024. }
  73025. if (!this._transformMatrices) {
  73026. this.prepare();
  73027. }
  73028. return this._transformMatrices;
  73029. };
  73030. Skeleton.prototype.getScene = function () {
  73031. return this._scene;
  73032. };
  73033. // Methods
  73034. /**
  73035. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  73036. */
  73037. Skeleton.prototype.toString = function (fullDetails) {
  73038. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  73039. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  73040. if (fullDetails) {
  73041. ret += ", Ranges: {";
  73042. var first = true;
  73043. for (var name_1 in this._ranges) {
  73044. if (first) {
  73045. ret += ", ";
  73046. first = false;
  73047. }
  73048. ret += name_1;
  73049. }
  73050. ret += "}";
  73051. }
  73052. return ret;
  73053. };
  73054. /**
  73055. * Get bone's index searching by name
  73056. * @param {string} name is bone's name to search for
  73057. * @return {number} Indice of the bone. Returns -1 if not found
  73058. */
  73059. Skeleton.prototype.getBoneIndexByName = function (name) {
  73060. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  73061. if (this.bones[boneIndex].name === name) {
  73062. return boneIndex;
  73063. }
  73064. }
  73065. return -1;
  73066. };
  73067. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  73068. // check name not already in use
  73069. if (!this._ranges[name]) {
  73070. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  73071. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73072. if (this.bones[i].animations[0]) {
  73073. this.bones[i].animations[0].createRange(name, from, to);
  73074. }
  73075. }
  73076. }
  73077. };
  73078. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  73079. if (deleteFrames === void 0) { deleteFrames = true; }
  73080. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73081. if (this.bones[i].animations[0]) {
  73082. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  73083. }
  73084. }
  73085. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  73086. };
  73087. Skeleton.prototype.getAnimationRange = function (name) {
  73088. return this._ranges[name];
  73089. };
  73090. /**
  73091. * Returns as an Array, all AnimationRanges defined on this skeleton
  73092. */
  73093. Skeleton.prototype.getAnimationRanges = function () {
  73094. var animationRanges = [];
  73095. var name;
  73096. var i = 0;
  73097. for (name in this._ranges) {
  73098. animationRanges[i] = this._ranges[name];
  73099. i++;
  73100. }
  73101. return animationRanges;
  73102. };
  73103. /**
  73104. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  73105. */
  73106. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  73107. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  73108. if (this._ranges[name] || !source.getAnimationRange(name)) {
  73109. return false;
  73110. }
  73111. var ret = true;
  73112. var frameOffset = this._getHighestAnimationFrame() + 1;
  73113. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  73114. var boneDict = {};
  73115. var sourceBones = source.bones;
  73116. var nBones;
  73117. var i;
  73118. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  73119. boneDict[sourceBones[i].name] = sourceBones[i];
  73120. }
  73121. if (this.bones.length !== sourceBones.length) {
  73122. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  73123. ret = false;
  73124. }
  73125. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  73126. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  73127. var boneName = this.bones[i].name;
  73128. var sourceBone = boneDict[boneName];
  73129. if (sourceBone) {
  73130. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  73131. }
  73132. else {
  73133. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  73134. ret = false;
  73135. }
  73136. }
  73137. // do not call createAnimationRange(), since it also is done to bones, which was already done
  73138. var range = source.getAnimationRange(name);
  73139. if (range) {
  73140. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  73141. }
  73142. return ret;
  73143. };
  73144. Skeleton.prototype.returnToRest = function () {
  73145. for (var index = 0; index < this.bones.length; index++) {
  73146. this.bones[index].returnToRest();
  73147. }
  73148. };
  73149. Skeleton.prototype._getHighestAnimationFrame = function () {
  73150. var ret = 0;
  73151. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73152. if (this.bones[i].animations[0]) {
  73153. var highest = this.bones[i].animations[0].getHighestFrame();
  73154. if (ret < highest) {
  73155. ret = highest;
  73156. }
  73157. }
  73158. }
  73159. return ret;
  73160. };
  73161. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  73162. var range = this.getAnimationRange(name);
  73163. if (!range) {
  73164. return null;
  73165. }
  73166. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  73167. };
  73168. Skeleton.prototype._markAsDirty = function () {
  73169. this._isDirty = true;
  73170. };
  73171. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  73172. this._meshesWithPoseMatrix.push(mesh);
  73173. };
  73174. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  73175. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  73176. if (index > -1) {
  73177. this._meshesWithPoseMatrix.splice(index, 1);
  73178. }
  73179. };
  73180. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  73181. this.onBeforeComputeObservable.notifyObservers(this);
  73182. for (var index = 0; index < this.bones.length; index++) {
  73183. var bone = this.bones[index];
  73184. var parentBone = bone.getParent();
  73185. if (parentBone) {
  73186. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  73187. }
  73188. else {
  73189. if (initialSkinMatrix) {
  73190. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  73191. }
  73192. else {
  73193. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  73194. }
  73195. }
  73196. if (bone._index !== -1) {
  73197. var mappedIndex = bone._index === null ? index : bone._index;
  73198. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  73199. }
  73200. }
  73201. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  73202. };
  73203. Skeleton.prototype.prepare = function () {
  73204. if (!this._isDirty) {
  73205. return;
  73206. }
  73207. if (this.needInitialSkinMatrix) {
  73208. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  73209. var mesh = this._meshesWithPoseMatrix[index];
  73210. var poseMatrix = mesh.getPoseMatrix();
  73211. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  73212. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73213. }
  73214. if (this._synchronizedWithMesh !== mesh) {
  73215. this._synchronizedWithMesh = mesh;
  73216. // Prepare bones
  73217. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  73218. var bone = this.bones[boneIndex];
  73219. if (!bone.getParent()) {
  73220. var matrix = bone.getBaseMatrix();
  73221. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  73222. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  73223. }
  73224. }
  73225. }
  73226. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  73227. }
  73228. }
  73229. else {
  73230. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  73231. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73232. }
  73233. this._computeTransformMatrices(this._transformMatrices, null);
  73234. }
  73235. this._isDirty = false;
  73236. this._scene._activeBones.addCount(this.bones.length, false);
  73237. };
  73238. Skeleton.prototype.getAnimatables = function () {
  73239. if (!this._animatables || this._animatables.length !== this.bones.length) {
  73240. this._animatables = [];
  73241. for (var index = 0; index < this.bones.length; index++) {
  73242. this._animatables.push(this.bones[index]);
  73243. }
  73244. }
  73245. return this._animatables;
  73246. };
  73247. Skeleton.prototype.clone = function (name, id) {
  73248. var result = new Skeleton(name, id || name, this._scene);
  73249. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73250. for (var index = 0; index < this.bones.length; index++) {
  73251. var source = this.bones[index];
  73252. var parentBone = null;
  73253. var parent_1 = source.getParent();
  73254. if (parent_1) {
  73255. var parentIndex = this.bones.indexOf(parent_1);
  73256. parentBone = result.bones[parentIndex];
  73257. }
  73258. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  73259. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  73260. }
  73261. if (this._ranges) {
  73262. result._ranges = {};
  73263. for (var rangeName in this._ranges) {
  73264. var range = this._ranges[rangeName];
  73265. if (range) {
  73266. result._ranges[rangeName] = range.clone();
  73267. }
  73268. }
  73269. }
  73270. this._isDirty = true;
  73271. return result;
  73272. };
  73273. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  73274. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  73275. this.bones.forEach(function (bone) {
  73276. bone.animations.forEach(function (animation) {
  73277. animation.enableBlending = true;
  73278. animation.blendingSpeed = blendingSpeed;
  73279. });
  73280. });
  73281. };
  73282. Skeleton.prototype.dispose = function () {
  73283. this._meshesWithPoseMatrix = [];
  73284. // Animations
  73285. this.getScene().stopAnimation(this);
  73286. // Remove from scene
  73287. this.getScene().removeSkeleton(this);
  73288. };
  73289. Skeleton.prototype.serialize = function () {
  73290. var serializationObject = {};
  73291. serializationObject.name = this.name;
  73292. serializationObject.id = this.id;
  73293. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  73294. serializationObject.bones = [];
  73295. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73296. for (var index = 0; index < this.bones.length; index++) {
  73297. var bone = this.bones[index];
  73298. var parent_2 = bone.getParent();
  73299. var serializedBone = {
  73300. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  73301. name: bone.name,
  73302. matrix: bone.getBaseMatrix().toArray(),
  73303. rest: bone.getRestPose().toArray()
  73304. };
  73305. serializationObject.bones.push(serializedBone);
  73306. if (bone.length) {
  73307. serializedBone.length = bone.length;
  73308. }
  73309. if (bone.animations && bone.animations.length > 0) {
  73310. serializedBone.animation = bone.animations[0].serialize();
  73311. }
  73312. serializationObject.ranges = [];
  73313. for (var name in this._ranges) {
  73314. var source = this._ranges[name];
  73315. if (!source) {
  73316. continue;
  73317. }
  73318. var range = {};
  73319. range.name = name;
  73320. range.from = source.from;
  73321. range.to = source.to;
  73322. serializationObject.ranges.push(range);
  73323. }
  73324. }
  73325. return serializationObject;
  73326. };
  73327. Skeleton.Parse = function (parsedSkeleton, scene) {
  73328. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  73329. if (parsedSkeleton.dimensionsAtRest) {
  73330. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  73331. }
  73332. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  73333. var index;
  73334. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  73335. var parsedBone = parsedSkeleton.bones[index];
  73336. var parentBone = null;
  73337. if (parsedBone.parentBoneIndex > -1) {
  73338. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  73339. }
  73340. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  73341. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  73342. if (parsedBone.length) {
  73343. bone.length = parsedBone.length;
  73344. }
  73345. if (parsedBone.animation) {
  73346. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  73347. }
  73348. }
  73349. // placed after bones, so createAnimationRange can cascade down
  73350. if (parsedSkeleton.ranges) {
  73351. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  73352. var data = parsedSkeleton.ranges[index];
  73353. skeleton.createAnimationRange(data.name, data.from, data.to);
  73354. }
  73355. }
  73356. return skeleton;
  73357. };
  73358. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  73359. if (forceUpdate === void 0) { forceUpdate = false; }
  73360. var renderId = this._scene.getRenderId();
  73361. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  73362. this.bones[0].computeAbsoluteTransforms();
  73363. this._lastAbsoluteTransformsUpdateId = renderId;
  73364. }
  73365. };
  73366. Skeleton.prototype.getPoseMatrix = function () {
  73367. var poseMatrix = null;
  73368. if (this._meshesWithPoseMatrix.length > 0) {
  73369. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  73370. }
  73371. return poseMatrix;
  73372. };
  73373. Skeleton.prototype.sortBones = function () {
  73374. var bones = new Array();
  73375. var visited = new Array(this.bones.length);
  73376. for (var index = 0; index < this.bones.length; index++) {
  73377. this._sortBones(index, bones, visited);
  73378. }
  73379. this.bones = bones;
  73380. };
  73381. Skeleton.prototype._sortBones = function (index, bones, visited) {
  73382. if (visited[index]) {
  73383. return;
  73384. }
  73385. visited[index] = true;
  73386. var bone = this.bones[index];
  73387. if (bone._index === undefined) {
  73388. bone._index = index;
  73389. }
  73390. var parentBone = bone.getParent();
  73391. if (parentBone) {
  73392. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  73393. }
  73394. bones.push(bone);
  73395. };
  73396. return Skeleton;
  73397. }());
  73398. BABYLON.Skeleton = Skeleton;
  73399. })(BABYLON || (BABYLON = {}));
  73400. //# sourceMappingURL=babylon.skeleton.js.map
  73401. "use strict";
  73402. var BABYLON;
  73403. (function (BABYLON) {
  73404. var SphericalPolynomial = /** @class */ (function () {
  73405. function SphericalPolynomial() {
  73406. this.x = BABYLON.Vector3.Zero();
  73407. this.y = BABYLON.Vector3.Zero();
  73408. this.z = BABYLON.Vector3.Zero();
  73409. this.xx = BABYLON.Vector3.Zero();
  73410. this.yy = BABYLON.Vector3.Zero();
  73411. this.zz = BABYLON.Vector3.Zero();
  73412. this.xy = BABYLON.Vector3.Zero();
  73413. this.yz = BABYLON.Vector3.Zero();
  73414. this.zx = BABYLON.Vector3.Zero();
  73415. }
  73416. SphericalPolynomial.prototype.addAmbient = function (color) {
  73417. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73418. this.xx = this.xx.add(colorVector);
  73419. this.yy = this.yy.add(colorVector);
  73420. this.zz = this.zz.add(colorVector);
  73421. };
  73422. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  73423. var result = new SphericalPolynomial();
  73424. result.x = harmonics.L11.scale(1.02333);
  73425. result.y = harmonics.L1_1.scale(1.02333);
  73426. result.z = harmonics.L10.scale(1.02333);
  73427. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  73428. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  73429. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  73430. result.yz = harmonics.L2_1.scale(0.858086);
  73431. result.zx = harmonics.L21.scale(0.858086);
  73432. result.xy = harmonics.L2_2.scale(0.858086);
  73433. result.scale(1.0 / Math.PI);
  73434. return result;
  73435. };
  73436. SphericalPolynomial.prototype.scale = function (scale) {
  73437. this.x = this.x.scale(scale);
  73438. this.y = this.y.scale(scale);
  73439. this.z = this.z.scale(scale);
  73440. this.xx = this.xx.scale(scale);
  73441. this.yy = this.yy.scale(scale);
  73442. this.zz = this.zz.scale(scale);
  73443. this.yz = this.yz.scale(scale);
  73444. this.zx = this.zx.scale(scale);
  73445. this.xy = this.xy.scale(scale);
  73446. };
  73447. return SphericalPolynomial;
  73448. }());
  73449. BABYLON.SphericalPolynomial = SphericalPolynomial;
  73450. var SphericalHarmonics = /** @class */ (function () {
  73451. function SphericalHarmonics() {
  73452. this.L00 = BABYLON.Vector3.Zero();
  73453. this.L1_1 = BABYLON.Vector3.Zero();
  73454. this.L10 = BABYLON.Vector3.Zero();
  73455. this.L11 = BABYLON.Vector3.Zero();
  73456. this.L2_2 = BABYLON.Vector3.Zero();
  73457. this.L2_1 = BABYLON.Vector3.Zero();
  73458. this.L20 = BABYLON.Vector3.Zero();
  73459. this.L21 = BABYLON.Vector3.Zero();
  73460. this.L22 = BABYLON.Vector3.Zero();
  73461. }
  73462. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  73463. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  73464. var c = colorVector.scale(deltaSolidAngle);
  73465. this.L00 = this.L00.add(c.scale(0.282095));
  73466. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  73467. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  73468. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  73469. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  73470. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  73471. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  73472. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  73473. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  73474. };
  73475. SphericalHarmonics.prototype.scale = function (scale) {
  73476. this.L00 = this.L00.scale(scale);
  73477. this.L1_1 = this.L1_1.scale(scale);
  73478. this.L10 = this.L10.scale(scale);
  73479. this.L11 = this.L11.scale(scale);
  73480. this.L2_2 = this.L2_2.scale(scale);
  73481. this.L2_1 = this.L2_1.scale(scale);
  73482. this.L20 = this.L20.scale(scale);
  73483. this.L21 = this.L21.scale(scale);
  73484. this.L22 = this.L22.scale(scale);
  73485. };
  73486. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  73487. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  73488. //
  73489. // E_lm = A_l * L_lm
  73490. //
  73491. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  73492. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  73493. // the scaling factors are given in equation 9.
  73494. // Constant (Band 0)
  73495. this.L00 = this.L00.scale(3.141593);
  73496. // Linear (Band 1)
  73497. this.L1_1 = this.L1_1.scale(2.094395);
  73498. this.L10 = this.L10.scale(2.094395);
  73499. this.L11 = this.L11.scale(2.094395);
  73500. // Quadratic (Band 2)
  73501. this.L2_2 = this.L2_2.scale(0.785398);
  73502. this.L2_1 = this.L2_1.scale(0.785398);
  73503. this.L20 = this.L20.scale(0.785398);
  73504. this.L21 = this.L21.scale(0.785398);
  73505. this.L22 = this.L22.scale(0.785398);
  73506. };
  73507. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  73508. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  73509. // L = (1/pi) * E * rho
  73510. //
  73511. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  73512. this.scale(1.0 / Math.PI);
  73513. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  73514. // (The pixel shader must apply albedo after texture fetches, etc).
  73515. };
  73516. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  73517. var result = new SphericalHarmonics();
  73518. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  73519. result.L1_1 = polynomial.y.scale(0.977204);
  73520. result.L10 = polynomial.z.scale(0.977204);
  73521. result.L11 = polynomial.x.scale(0.977204);
  73522. result.L2_2 = polynomial.xy.scale(1.16538);
  73523. result.L2_1 = polynomial.yz.scale(1.16538);
  73524. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  73525. result.L21 = polynomial.zx.scale(1.16538);
  73526. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  73527. result.scale(Math.PI);
  73528. return result;
  73529. };
  73530. return SphericalHarmonics;
  73531. }());
  73532. BABYLON.SphericalHarmonics = SphericalHarmonics;
  73533. })(BABYLON || (BABYLON = {}));
  73534. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  73535. "use strict";
  73536. var BABYLON;
  73537. (function (BABYLON) {
  73538. var FileFaceOrientation = /** @class */ (function () {
  73539. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  73540. this.name = name;
  73541. this.worldAxisForNormal = worldAxisForNormal;
  73542. this.worldAxisForFileX = worldAxisForFileX;
  73543. this.worldAxisForFileY = worldAxisForFileY;
  73544. }
  73545. return FileFaceOrientation;
  73546. }());
  73547. ;
  73548. /**
  73549. * Helper class dealing with the extraction of spherical polynomial dataArray
  73550. * from a cube map.
  73551. */
  73552. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  73553. function CubeMapToSphericalPolynomialTools() {
  73554. }
  73555. /**
  73556. * Converts a texture to the according Spherical Polynomial data.
  73557. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73558. *
  73559. * @param texture The texture to extract the information from.
  73560. * @return The Spherical Polynomial data.
  73561. */
  73562. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  73563. if (!texture.isCube) {
  73564. // Only supports cube Textures currently.
  73565. return null;
  73566. }
  73567. var size = texture.getSize().width;
  73568. var right = texture.readPixels(0);
  73569. var left = texture.readPixels(1);
  73570. var up;
  73571. var down;
  73572. if (texture.isRenderTarget) {
  73573. up = texture.readPixels(3);
  73574. down = texture.readPixels(2);
  73575. }
  73576. else {
  73577. up = texture.readPixels(2);
  73578. down = texture.readPixels(3);
  73579. }
  73580. var front = texture.readPixels(4);
  73581. var back = texture.readPixels(5);
  73582. var gammaSpace = texture.gammaSpace;
  73583. // Always read as RGBA.
  73584. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  73585. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  73586. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73587. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  73588. }
  73589. var cubeInfo = {
  73590. size: size,
  73591. right: right,
  73592. left: left,
  73593. up: up,
  73594. down: down,
  73595. front: front,
  73596. back: back,
  73597. format: format,
  73598. type: type,
  73599. gammaSpace: gammaSpace,
  73600. };
  73601. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  73602. };
  73603. /**
  73604. * Converts a cubemap to the according Spherical Polynomial data.
  73605. * This extracts the first 3 orders only as they are the only one used in the lighting.
  73606. *
  73607. * @param cubeInfo The Cube map to extract the information from.
  73608. * @return The Spherical Polynomial data.
  73609. */
  73610. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  73611. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  73612. var totalSolidAngle = 0.0;
  73613. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  73614. var du = 2.0 / cubeInfo.size;
  73615. var dv = du;
  73616. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  73617. var minUV = du * 0.5 - 1.0;
  73618. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  73619. var fileFace = this.FileFaces[faceIndex];
  73620. var dataArray = cubeInfo[fileFace.name];
  73621. var v = minUV;
  73622. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  73623. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  73624. // Because SP is still linear, so summation is fine in that basis.
  73625. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  73626. for (var y = 0; y < cubeInfo.size; y++) {
  73627. var u = minUV;
  73628. for (var x = 0; x < cubeInfo.size; x++) {
  73629. // World direction (not normalised)
  73630. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  73631. worldDirection.normalize();
  73632. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  73633. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  73634. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  73635. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  73636. // Handle Integer types.
  73637. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  73638. r /= 255;
  73639. g /= 255;
  73640. b /= 255;
  73641. }
  73642. // Handle Gamma space textures.
  73643. if (cubeInfo.gammaSpace) {
  73644. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  73645. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  73646. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  73647. }
  73648. var color = new BABYLON.Color3(r, g, b);
  73649. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  73650. totalSolidAngle += deltaSolidAngle;
  73651. u += du;
  73652. }
  73653. v += dv;
  73654. }
  73655. }
  73656. // Solid angle for entire sphere is 4*pi
  73657. var sphereSolidAngle = 4.0 * Math.PI;
  73658. // Adjust the solid angle to allow for how many faces we processed.
  73659. var facesProcessed = 6.0;
  73660. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  73661. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  73662. // This is needed because the numerical integration over the cube uses a
  73663. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  73664. // and also to compensate for accumulative error due to float precision in the summation.
  73665. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  73666. sphericalHarmonics.scale(correctionFactor);
  73667. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  73668. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  73669. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  73670. };
  73671. CubeMapToSphericalPolynomialTools.FileFaces = [
  73672. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  73673. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  73674. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  73675. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  73676. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  73677. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  73678. ];
  73679. return CubeMapToSphericalPolynomialTools;
  73680. }());
  73681. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  73682. })(BABYLON || (BABYLON = {}));
  73683. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  73684. "use strict";
  73685. var BABYLON;
  73686. (function (BABYLON) {
  73687. /**
  73688. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  73689. */
  73690. var PanoramaToCubeMapTools = /** @class */ (function () {
  73691. function PanoramaToCubeMapTools() {
  73692. }
  73693. /**
  73694. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  73695. *
  73696. * @param float32Array The source data.
  73697. * @param inputWidth The width of the input panorama.
  73698. * @param inputhHeight The height of the input panorama.
  73699. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  73700. * @return The cubemap data
  73701. */
  73702. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  73703. if (!float32Array) {
  73704. throw "ConvertPanoramaToCubemap: input cannot be null";
  73705. }
  73706. if (float32Array.length != inputWidth * inputHeight * 3) {
  73707. throw "ConvertPanoramaToCubemap: input size is wrong";
  73708. }
  73709. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  73710. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  73711. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  73712. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  73713. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  73714. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  73715. return {
  73716. front: textureFront,
  73717. back: textureBack,
  73718. left: textureLeft,
  73719. right: textureRight,
  73720. up: textureUp,
  73721. down: textureDown,
  73722. size: size,
  73723. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  73724. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  73725. gammaSpace: false,
  73726. };
  73727. };
  73728. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  73729. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  73730. var textureArray = new Float32Array(buffer);
  73731. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  73732. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  73733. var dy = 1 / texSize;
  73734. var fy = 0;
  73735. for (var y = 0; y < texSize; y++) {
  73736. var xv1 = faceData[0];
  73737. var xv2 = faceData[2];
  73738. for (var x = 0; x < texSize; x++) {
  73739. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  73740. v.normalize();
  73741. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  73742. // 3 channels per pixels
  73743. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  73744. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  73745. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  73746. xv1 = xv1.add(rotDX1);
  73747. xv2 = xv2.add(rotDX2);
  73748. }
  73749. fy += dy;
  73750. }
  73751. return textureArray;
  73752. };
  73753. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  73754. var theta = Math.atan2(vDir.z, vDir.x);
  73755. var phi = Math.acos(vDir.y);
  73756. while (theta < -Math.PI)
  73757. theta += 2 * Math.PI;
  73758. while (theta > Math.PI)
  73759. theta -= 2 * Math.PI;
  73760. var dx = theta / Math.PI;
  73761. var dy = phi / Math.PI;
  73762. // recenter.
  73763. dx = dx * 0.5 + 0.5;
  73764. var px = Math.round(dx * inputWidth);
  73765. if (px < 0)
  73766. px = 0;
  73767. else if (px >= inputWidth)
  73768. px = inputWidth - 1;
  73769. var py = Math.round(dy * inputHeight);
  73770. if (py < 0)
  73771. py = 0;
  73772. else if (py >= inputHeight)
  73773. py = inputHeight - 1;
  73774. var inputY = (inputHeight - py - 1);
  73775. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  73776. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  73777. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  73778. return {
  73779. r: r,
  73780. g: g,
  73781. b: b
  73782. };
  73783. };
  73784. PanoramaToCubeMapTools.FACE_FRONT = [
  73785. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73786. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73787. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73788. new BABYLON.Vector3(1.0, 1.0, -1.0)
  73789. ];
  73790. PanoramaToCubeMapTools.FACE_BACK = [
  73791. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73792. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73793. new BABYLON.Vector3(1.0, 1.0, 1.0),
  73794. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  73795. ];
  73796. PanoramaToCubeMapTools.FACE_RIGHT = [
  73797. new BABYLON.Vector3(1.0, -1.0, -1.0),
  73798. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73799. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73800. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73801. ];
  73802. PanoramaToCubeMapTools.FACE_LEFT = [
  73803. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73804. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73805. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73806. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  73807. ];
  73808. PanoramaToCubeMapTools.FACE_DOWN = [
  73809. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  73810. new BABYLON.Vector3(1.0, 1.0, -1.0),
  73811. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  73812. new BABYLON.Vector3(1.0, 1.0, 1.0)
  73813. ];
  73814. PanoramaToCubeMapTools.FACE_UP = [
  73815. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  73816. new BABYLON.Vector3(1.0, -1.0, 1.0),
  73817. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  73818. new BABYLON.Vector3(1.0, -1.0, -1.0)
  73819. ];
  73820. return PanoramaToCubeMapTools;
  73821. }());
  73822. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  73823. })(BABYLON || (BABYLON = {}));
  73824. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  73825. "use strict";
  73826. var BABYLON;
  73827. (function (BABYLON) {
  73828. ;
  73829. /**
  73830. * This groups tools to convert HDR texture to native colors array.
  73831. */
  73832. var HDRTools = /** @class */ (function () {
  73833. function HDRTools() {
  73834. }
  73835. HDRTools.Ldexp = function (mantissa, exponent) {
  73836. if (exponent > 1023) {
  73837. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  73838. }
  73839. if (exponent < -1074) {
  73840. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  73841. }
  73842. return mantissa * Math.pow(2, exponent);
  73843. };
  73844. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  73845. if (exponent > 0) {
  73846. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  73847. float32array[index + 0] = red * exponent;
  73848. float32array[index + 1] = green * exponent;
  73849. float32array[index + 2] = blue * exponent;
  73850. }
  73851. else {
  73852. float32array[index + 0] = 0;
  73853. float32array[index + 1] = 0;
  73854. float32array[index + 2] = 0;
  73855. }
  73856. };
  73857. HDRTools.readStringLine = function (uint8array, startIndex) {
  73858. var line = "";
  73859. var character = "";
  73860. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  73861. character = String.fromCharCode(uint8array[i]);
  73862. if (character == "\n") {
  73863. break;
  73864. }
  73865. line += character;
  73866. }
  73867. return line;
  73868. };
  73869. /**
  73870. * Reads header information from an RGBE texture stored in a native array.
  73871. * More information on this format are available here:
  73872. * https://en.wikipedia.org/wiki/RGBE_image_format
  73873. *
  73874. * @param uint8array The binary file stored in native array.
  73875. * @return The header information.
  73876. */
  73877. HDRTools.RGBE_ReadHeader = function (uint8array) {
  73878. var height = 0;
  73879. var width = 0;
  73880. var line = this.readStringLine(uint8array, 0);
  73881. if (line[0] != '#' || line[1] != '?') {
  73882. throw "Bad HDR Format.";
  73883. }
  73884. var endOfHeader = false;
  73885. var findFormat = false;
  73886. var lineIndex = 0;
  73887. do {
  73888. lineIndex += (line.length + 1);
  73889. line = this.readStringLine(uint8array, lineIndex);
  73890. if (line == "FORMAT=32-bit_rle_rgbe") {
  73891. findFormat = true;
  73892. }
  73893. else if (line.length == 0) {
  73894. endOfHeader = true;
  73895. }
  73896. } while (!endOfHeader);
  73897. if (!findFormat) {
  73898. throw "HDR Bad header format, unsupported FORMAT";
  73899. }
  73900. lineIndex += (line.length + 1);
  73901. line = this.readStringLine(uint8array, lineIndex);
  73902. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  73903. var match = sizeRegexp.exec(line);
  73904. // TODO. Support +Y and -X if needed.
  73905. if (!match || match.length < 3) {
  73906. throw "HDR Bad header format, no size";
  73907. }
  73908. width = parseInt(match[2]);
  73909. height = parseInt(match[1]);
  73910. if (width < 8 || width > 0x7fff) {
  73911. throw "HDR Bad header format, unsupported size";
  73912. }
  73913. lineIndex += (line.length + 1);
  73914. return {
  73915. height: height,
  73916. width: width,
  73917. dataPosition: lineIndex
  73918. };
  73919. };
  73920. /**
  73921. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  73922. * This RGBE texture needs to store the information as a panorama.
  73923. *
  73924. * More information on this format are available here:
  73925. * https://en.wikipedia.org/wiki/RGBE_image_format
  73926. *
  73927. * @param buffer The binary file stored in an array buffer.
  73928. * @param size The expected size of the extracted cubemap.
  73929. * @return The Cube Map information.
  73930. */
  73931. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  73932. var uint8array = new Uint8Array(buffer);
  73933. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  73934. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73935. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  73936. return cubeMapData;
  73937. };
  73938. /**
  73939. * Returns the pixels data extracted from an RGBE texture.
  73940. * This pixels will be stored left to right up to down in the R G B order in one array.
  73941. *
  73942. * More information on this format are available here:
  73943. * https://en.wikipedia.org/wiki/RGBE_image_format
  73944. *
  73945. * @param uint8array The binary file stored in an array buffer.
  73946. * @param hdrInfo The header information of the file.
  73947. * @return The pixels data in RGB right to left up to down order.
  73948. */
  73949. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  73950. // Keep for multi format supports.
  73951. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  73952. };
  73953. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  73954. var num_scanlines = hdrInfo.height;
  73955. var scanline_width = hdrInfo.width;
  73956. var a, b, c, d, count;
  73957. var dataIndex = hdrInfo.dataPosition;
  73958. var index = 0, endIndex = 0, i = 0;
  73959. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  73960. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  73961. // 3 channels of 4 bytes per pixel in float.
  73962. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  73963. var resultArray = new Float32Array(resultBuffer);
  73964. // read in each successive scanline
  73965. while (num_scanlines > 0) {
  73966. a = uint8array[dataIndex++];
  73967. b = uint8array[dataIndex++];
  73968. c = uint8array[dataIndex++];
  73969. d = uint8array[dataIndex++];
  73970. if (a != 2 || b != 2 || (c & 0x80)) {
  73971. // this file is not run length encoded
  73972. throw "HDR Bad header format, not RLE";
  73973. }
  73974. if (((c << 8) | d) != scanline_width) {
  73975. throw "HDR Bad header format, wrong scan line width";
  73976. }
  73977. index = 0;
  73978. // read each of the four channels for the scanline into the buffer
  73979. for (i = 0; i < 4; i++) {
  73980. endIndex = (i + 1) * scanline_width;
  73981. while (index < endIndex) {
  73982. a = uint8array[dataIndex++];
  73983. b = uint8array[dataIndex++];
  73984. if (a > 128) {
  73985. // a run of the same value
  73986. count = a - 128;
  73987. if ((count == 0) || (count > endIndex - index)) {
  73988. throw "HDR Bad Format, bad scanline data (run)";
  73989. }
  73990. while (count-- > 0) {
  73991. scanLineArray[index++] = b;
  73992. }
  73993. }
  73994. else {
  73995. // a non-run
  73996. count = a;
  73997. if ((count == 0) || (count > endIndex - index)) {
  73998. throw "HDR Bad Format, bad scanline data (non-run)";
  73999. }
  74000. scanLineArray[index++] = b;
  74001. if (--count > 0) {
  74002. for (var j = 0; j < count; j++) {
  74003. scanLineArray[index++] = uint8array[dataIndex++];
  74004. }
  74005. }
  74006. }
  74007. }
  74008. }
  74009. // now convert data from buffer into floats
  74010. for (i = 0; i < scanline_width; i++) {
  74011. a = scanLineArray[i];
  74012. b = scanLineArray[i + scanline_width];
  74013. c = scanLineArray[i + 2 * scanline_width];
  74014. d = scanLineArray[i + 3 * scanline_width];
  74015. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  74016. }
  74017. num_scanlines--;
  74018. }
  74019. return resultArray;
  74020. };
  74021. return HDRTools;
  74022. }());
  74023. BABYLON.HDRTools = HDRTools;
  74024. })(BABYLON || (BABYLON = {}));
  74025. //# sourceMappingURL=babylon.hdr.js.map
  74026. "use strict";
  74027. var BABYLON;
  74028. (function (BABYLON) {
  74029. /**
  74030. * This represents a texture coming from an HDR input.
  74031. *
  74032. * The only supported format is currently panorama picture stored in RGBE format.
  74033. * Example of such files can be found on HDRLib: http://hdrlib.com/
  74034. */
  74035. var HDRCubeTexture = /** @class */ (function (_super) {
  74036. __extends(HDRCubeTexture, _super);
  74037. /**
  74038. * Instantiates an HDRTexture from the following parameters.
  74039. *
  74040. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  74041. * @param scene The scene the texture will be used in
  74042. * @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.
  74043. * @param noMipmap Forces to not generate the mipmap if true
  74044. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  74045. * @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)
  74046. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  74047. */
  74048. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  74049. if (noMipmap === void 0) { noMipmap = false; }
  74050. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74051. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74052. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74053. if (onLoad === void 0) { onLoad = null; }
  74054. if (onError === void 0) { onError = null; }
  74055. var _this = _super.call(this, scene) || this;
  74056. _this._useInGammaSpace = false;
  74057. _this._generateHarmonics = true;
  74058. _this._isBABYLONPreprocessed = false;
  74059. _this._onLoad = null;
  74060. _this._onError = null;
  74061. /**
  74062. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  74063. */
  74064. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  74065. /**
  74066. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  74067. * This is usefull at run time to apply the good shader.
  74068. */
  74069. _this.isPMREM = false;
  74070. _this._isBlocking = true;
  74071. /**
  74072. * Gets or sets the center of the bounding box associated with the cube texture
  74073. * It must define where the camera used to render the texture was set
  74074. */
  74075. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  74076. if (!url) {
  74077. return _this;
  74078. }
  74079. _this.name = url;
  74080. _this.url = url;
  74081. _this.hasAlpha = false;
  74082. _this.isCube = true;
  74083. _this._textureMatrix = BABYLON.Matrix.Identity();
  74084. _this._onLoad = onLoad;
  74085. _this._onError = onError;
  74086. _this.gammaSpace = false;
  74087. var caps = scene.getEngine().getCaps();
  74088. if (size) {
  74089. _this._isBABYLONPreprocessed = false;
  74090. _this._noMipmap = noMipmap;
  74091. _this._size = size;
  74092. _this._useInGammaSpace = useInGammaSpace;
  74093. _this._usePMREMGenerator = usePMREMGenerator &&
  74094. caps.textureLOD &&
  74095. caps.textureFloat &&
  74096. !_this._useInGammaSpace;
  74097. }
  74098. else {
  74099. _this._isBABYLONPreprocessed = true;
  74100. _this._noMipmap = false;
  74101. _this._useInGammaSpace = false;
  74102. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  74103. !_this._useInGammaSpace;
  74104. }
  74105. _this.isPMREM = _this._usePMREMGenerator;
  74106. _this._texture = _this._getFromCache(url, _this._noMipmap);
  74107. if (!_this._texture) {
  74108. if (!scene.useDelayedTextureLoading) {
  74109. _this.loadTexture();
  74110. }
  74111. else {
  74112. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  74113. }
  74114. }
  74115. return _this;
  74116. }
  74117. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  74118. /**
  74119. * Gets wether or not the texture is blocking during loading.
  74120. */
  74121. get: function () {
  74122. return this._isBlocking;
  74123. },
  74124. /**
  74125. * Sets wether or not the texture is blocking during loading.
  74126. */
  74127. set: function (value) {
  74128. this._isBlocking = value;
  74129. },
  74130. enumerable: true,
  74131. configurable: true
  74132. });
  74133. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  74134. get: function () {
  74135. return this._boundingBoxSize;
  74136. },
  74137. /**
  74138. * Gets or sets the size of the bounding box associated with the cube texture
  74139. * When defined, the cubemap will switch to local mode
  74140. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  74141. * @example https://www.babylonjs-playground.com/#RNASML
  74142. */
  74143. set: function (value) {
  74144. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  74145. return;
  74146. }
  74147. this._boundingBoxSize = value;
  74148. var scene = this.getScene();
  74149. if (scene) {
  74150. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  74151. }
  74152. },
  74153. enumerable: true,
  74154. configurable: true
  74155. });
  74156. /**
  74157. * Occurs when the file is a preprocessed .babylon.hdr file.
  74158. */
  74159. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  74160. var _this = this;
  74161. var mipLevels = 0;
  74162. var floatArrayView = null;
  74163. var scene = this.getScene();
  74164. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  74165. var mips = new Array();
  74166. if (!floatArrayView) {
  74167. return mips;
  74168. }
  74169. var startIndex = 30;
  74170. for (var level = 0; level < mipLevels; level++) {
  74171. mips.push([]);
  74172. // Fill each pixel of the mip level.
  74173. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  74174. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74175. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  74176. mips[level].push(faceData);
  74177. startIndex += faceSize;
  74178. }
  74179. }
  74180. return mips;
  74181. } : null;
  74182. var callback = function (buffer) {
  74183. var scene = _this.getScene();
  74184. if (!scene) {
  74185. return null;
  74186. }
  74187. // Create Native Array Views
  74188. var intArrayView = new Int32Array(buffer);
  74189. floatArrayView = new Float32Array(buffer);
  74190. // Fill header.
  74191. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  74192. _this._size = intArrayView[1]; // CubeMap max mip face size.
  74193. // Update Texture Information.
  74194. if (!_this._texture) {
  74195. return null;
  74196. }
  74197. _this._texture.updateSize(_this._size, _this._size);
  74198. // Fill polynomial information.
  74199. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  74200. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  74201. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  74202. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  74203. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  74204. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  74205. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  74206. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  74207. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  74208. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  74209. _this.sphericalPolynomial = sphericalPolynomial;
  74210. // Fill pixel data.
  74211. mipLevels = intArrayView[29]; // Number of mip levels.
  74212. var startIndex = 30;
  74213. var data = [];
  74214. var faceSize = Math.pow(_this._size, 2) * 3;
  74215. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74216. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  74217. startIndex += faceSize;
  74218. }
  74219. var results = [];
  74220. var byteArray = null;
  74221. // Push each faces.
  74222. for (var k = 0; k < 6; k++) {
  74223. var dataFace = null;
  74224. // To be deprecated.
  74225. if (version === 1) {
  74226. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  74227. dataFace = data[j];
  74228. }
  74229. // If special cases.
  74230. if (!mipmapGenerator && dataFace) {
  74231. if (!scene.getEngine().getCaps().textureFloat) {
  74232. // 3 channels of 1 bytes per pixel in bytes.
  74233. var byteBuffer = new ArrayBuffer(faceSize);
  74234. byteArray = new Uint8Array(byteBuffer);
  74235. }
  74236. for (var i = 0; i < _this._size * _this._size; i++) {
  74237. // Put in gamma space if requested.
  74238. if (_this._useInGammaSpace) {
  74239. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74240. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74241. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74242. }
  74243. // Convert to int texture for fallback.
  74244. if (byteArray) {
  74245. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74246. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74247. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74248. // May use luminance instead if the result is not accurate.
  74249. var max = Math.max(Math.max(r, g), b);
  74250. if (max > 255) {
  74251. var scale = 255 / max;
  74252. r *= scale;
  74253. g *= scale;
  74254. b *= scale;
  74255. }
  74256. byteArray[(i * 3) + 0] = r;
  74257. byteArray[(i * 3) + 1] = g;
  74258. byteArray[(i * 3) + 2] = b;
  74259. }
  74260. }
  74261. }
  74262. // Fill the array accordingly.
  74263. if (byteArray) {
  74264. results.push(byteArray);
  74265. }
  74266. else {
  74267. results.push(dataFace);
  74268. }
  74269. }
  74270. return results;
  74271. };
  74272. if (scene) {
  74273. 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);
  74274. }
  74275. };
  74276. /**
  74277. * Occurs when the file is raw .hdr file.
  74278. */
  74279. HDRCubeTexture.prototype.loadHDRTexture = function () {
  74280. var _this = this;
  74281. var callback = function (buffer) {
  74282. var scene = _this.getScene();
  74283. if (!scene) {
  74284. return null;
  74285. }
  74286. // Extract the raw linear data.
  74287. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  74288. // Generate harmonics if needed.
  74289. if (_this._generateHarmonics) {
  74290. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  74291. _this.sphericalPolynomial = sphericalPolynomial;
  74292. }
  74293. var results = [];
  74294. var byteArray = null;
  74295. // Push each faces.
  74296. for (var j = 0; j < 6; j++) {
  74297. // Create uintarray fallback.
  74298. if (!scene.getEngine().getCaps().textureFloat) {
  74299. // 3 channels of 1 bytes per pixel in bytes.
  74300. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  74301. byteArray = new Uint8Array(byteBuffer);
  74302. }
  74303. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  74304. // If special cases.
  74305. if (_this._useInGammaSpace || byteArray) {
  74306. for (var i = 0; i < _this._size * _this._size; i++) {
  74307. // Put in gamma space if requested.
  74308. if (_this._useInGammaSpace) {
  74309. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74310. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74311. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74312. }
  74313. // Convert to int texture for fallback.
  74314. if (byteArray) {
  74315. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74316. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74317. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74318. // May use luminance instead if the result is not accurate.
  74319. var max = Math.max(Math.max(r, g), b);
  74320. if (max > 255) {
  74321. var scale = 255 / max;
  74322. r *= scale;
  74323. g *= scale;
  74324. b *= scale;
  74325. }
  74326. byteArray[(i * 3) + 0] = r;
  74327. byteArray[(i * 3) + 1] = g;
  74328. byteArray[(i * 3) + 2] = b;
  74329. }
  74330. }
  74331. }
  74332. if (byteArray) {
  74333. results.push(byteArray);
  74334. }
  74335. else {
  74336. results.push(dataFace);
  74337. }
  74338. }
  74339. return results;
  74340. };
  74341. var mipmapGenerator = null;
  74342. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  74343. // if (!this._noMipmap &&
  74344. // this._usePMREMGenerator) {
  74345. // mipmapGenerator = (data: ArrayBufferView[]) => {
  74346. // // Custom setup of the generator matching with the PBR shader values.
  74347. // var generator = new BABYLON.PMREMGenerator(data,
  74348. // this._size,
  74349. // this._size,
  74350. // 0,
  74351. // 3,
  74352. // this.getScene().getEngine().getCaps().textureFloat,
  74353. // 2048,
  74354. // 0.25,
  74355. // false,
  74356. // true);
  74357. // return generator.filterCubeMap();
  74358. // };
  74359. // }
  74360. var scene = this.getScene();
  74361. if (scene) {
  74362. 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);
  74363. }
  74364. };
  74365. /**
  74366. * Starts the loading process of the texture.
  74367. */
  74368. HDRCubeTexture.prototype.loadTexture = function () {
  74369. if (this._isBABYLONPreprocessed) {
  74370. this.loadBabylonTexture();
  74371. }
  74372. else {
  74373. this.loadHDRTexture();
  74374. }
  74375. };
  74376. HDRCubeTexture.prototype.clone = function () {
  74377. var scene = this.getScene();
  74378. if (!scene) {
  74379. return this;
  74380. }
  74381. var size = (this._isBABYLONPreprocessed ? null : this._size);
  74382. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  74383. // Base texture
  74384. newTexture.level = this.level;
  74385. newTexture.wrapU = this.wrapU;
  74386. newTexture.wrapV = this.wrapV;
  74387. newTexture.coordinatesIndex = this.coordinatesIndex;
  74388. newTexture.coordinatesMode = this.coordinatesMode;
  74389. return newTexture;
  74390. };
  74391. // Methods
  74392. HDRCubeTexture.prototype.delayLoad = function () {
  74393. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  74394. return;
  74395. }
  74396. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  74397. this._texture = this._getFromCache(this.url, this._noMipmap);
  74398. if (!this._texture) {
  74399. this.loadTexture();
  74400. }
  74401. };
  74402. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  74403. return this._textureMatrix;
  74404. };
  74405. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  74406. this._textureMatrix = value;
  74407. };
  74408. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  74409. var texture = null;
  74410. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  74411. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  74412. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  74413. texture.name = parsedTexture.name;
  74414. texture.hasAlpha = parsedTexture.hasAlpha;
  74415. texture.level = parsedTexture.level;
  74416. texture.coordinatesMode = parsedTexture.coordinatesMode;
  74417. texture.isBlocking = parsedTexture.isBlocking;
  74418. }
  74419. if (texture) {
  74420. if (parsedTexture.boundingBoxPosition) {
  74421. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  74422. }
  74423. if (parsedTexture.boundingBoxSize) {
  74424. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  74425. }
  74426. }
  74427. return texture;
  74428. };
  74429. HDRCubeTexture.prototype.serialize = function () {
  74430. if (!this.name) {
  74431. return null;
  74432. }
  74433. var serializationObject = {};
  74434. serializationObject.name = this.name;
  74435. serializationObject.hasAlpha = this.hasAlpha;
  74436. serializationObject.isCube = true;
  74437. serializationObject.level = this.level;
  74438. serializationObject.size = this._size;
  74439. serializationObject.coordinatesMode = this.coordinatesMode;
  74440. serializationObject.useInGammaSpace = this._useInGammaSpace;
  74441. serializationObject.generateHarmonics = this._generateHarmonics;
  74442. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  74443. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  74444. serializationObject.customType = "BABYLON.HDRCubeTexture";
  74445. serializationObject.noMipmap = this._noMipmap;
  74446. serializationObject.isBlocking = this._isBlocking;
  74447. return serializationObject;
  74448. };
  74449. /**
  74450. * Saves as a file the data contained in the texture in a binary format.
  74451. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74452. * as the spherical used in the lighting.
  74453. * @param url The HDR file url.
  74454. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74455. * @param onError Method called if any error happens during download.
  74456. * @return The packed binary data.
  74457. */
  74458. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  74459. if (onError === void 0) { onError = null; }
  74460. var callback = function (buffer) {
  74461. var data = new Blob([buffer], { type: 'application/octet-stream' });
  74462. // Returns a URL you can use as a href.
  74463. var objUrl = window.URL.createObjectURL(data);
  74464. // Simulates a link to it and click to dowload.
  74465. var a = document.createElement("a");
  74466. document.body.appendChild(a);
  74467. a.style.display = "none";
  74468. a.href = objUrl;
  74469. a.download = "envmap.babylon.hdr";
  74470. a.click();
  74471. };
  74472. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  74473. };
  74474. /**
  74475. * Serializes the data contained in the texture in a binary format.
  74476. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  74477. * as the spherical used in the lighting.
  74478. * @param url The HDR file url.
  74479. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  74480. * @param onError Method called if any error happens during download.
  74481. * @return The packed binary data.
  74482. */
  74483. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  74484. if (onError === void 0) { onError = null; }
  74485. // Needs the url tho create the texture.
  74486. if (!url) {
  74487. return;
  74488. }
  74489. // Check Power of two size.
  74490. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  74491. return;
  74492. }
  74493. // Coming Back in 3.x.
  74494. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  74495. };
  74496. HDRCubeTexture._facesMapping = [
  74497. "right",
  74498. "left",
  74499. "up",
  74500. "down",
  74501. "front",
  74502. "back"
  74503. ];
  74504. return HDRCubeTexture;
  74505. }(BABYLON.BaseTexture));
  74506. BABYLON.HDRCubeTexture = HDRCubeTexture;
  74507. })(BABYLON || (BABYLON = {}));
  74508. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  74509. "use strict";
  74510. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  74511. // Huge respect for a such great lib.
  74512. // Earcut license:
  74513. // Copyright (c) 2016, Mapbox
  74514. //
  74515. // Permission to use, copy, modify, and/or distribute this software for any purpose
  74516. // with or without fee is hereby granted, provided that the above copyright notice
  74517. // and this permission notice appear in all copies.
  74518. //
  74519. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  74520. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  74521. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  74522. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  74523. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  74524. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  74525. // THIS SOFTWARE.
  74526. var Earcut;
  74527. (function (Earcut) {
  74528. /**
  74529. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  74530. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  74531. * @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).
  74532. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  74533. */
  74534. function earcut(data, holeIndices, dim) {
  74535. dim = dim || 2;
  74536. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  74537. if (!outerNode)
  74538. return triangles;
  74539. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  74540. if (hasHoles)
  74541. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  74542. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  74543. if (data.length > 80 * dim) {
  74544. minX = maxX = data[0];
  74545. minY = maxY = data[1];
  74546. for (var i = dim; i < outerLen; i += dim) {
  74547. x = data[i];
  74548. y = data[i + 1];
  74549. if (x < minX)
  74550. minX = x;
  74551. if (y < minY)
  74552. minY = y;
  74553. if (x > maxX)
  74554. maxX = x;
  74555. if (y > maxY)
  74556. maxY = y;
  74557. }
  74558. // minX, minY and size are later used to transform coords into integers for z-order calculation
  74559. size = Math.max(maxX - minX, maxY - minY);
  74560. }
  74561. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  74562. return triangles;
  74563. }
  74564. Earcut.earcut = earcut;
  74565. var Node = /** @class */ (function () {
  74566. function Node(i, x, y) {
  74567. this.i = i;
  74568. this.x = x;
  74569. this.y = y;
  74570. this.prev = null;
  74571. this.next = null;
  74572. this.z = null;
  74573. this.prevZ = null;
  74574. this.nextZ = null;
  74575. this.steiner = false;
  74576. }
  74577. return Node;
  74578. }());
  74579. // create a circular doubly linked list from polygon points in the specified winding order
  74580. function linkedList(data, start, end, dim, clockwise) {
  74581. var i, last = null;
  74582. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  74583. for (i = start; i < end; i += dim)
  74584. last = insertNode(i, data[i], data[i + 1], last);
  74585. }
  74586. else {
  74587. for (i = end - dim; i >= start; i -= dim)
  74588. last = insertNode(i, data[i], data[i + 1], last);
  74589. }
  74590. if (last && equals(last, last.next)) {
  74591. removeNode(last);
  74592. last = last.next;
  74593. }
  74594. return last;
  74595. }
  74596. // eliminate colinear or duplicate points
  74597. function filterPoints(start, end) {
  74598. if (!start)
  74599. return start;
  74600. if (!end)
  74601. end = start;
  74602. var p = start, again;
  74603. do {
  74604. again = false;
  74605. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  74606. removeNode(p);
  74607. p = end = p.prev;
  74608. if (p === p.next)
  74609. return undefined;
  74610. again = true;
  74611. }
  74612. else {
  74613. p = p.next;
  74614. }
  74615. } while (again || p !== end);
  74616. return end;
  74617. }
  74618. // main ear slicing loop which triangulates a polygon (given as a linked list)
  74619. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  74620. if (!ear)
  74621. return;
  74622. // interlink polygon nodes in z-order
  74623. if (!pass && size)
  74624. indexCurve(ear, minX, minY, size);
  74625. var stop = ear, prev, next;
  74626. // iterate through ears, slicing them one by one
  74627. while (ear.prev !== ear.next) {
  74628. prev = ear.prev;
  74629. next = ear.next;
  74630. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  74631. // cut off the triangle
  74632. triangles.push(prev.i / dim);
  74633. triangles.push(ear.i / dim);
  74634. triangles.push(next.i / dim);
  74635. removeNode(ear);
  74636. // skipping the next vertice leads to less sliver triangles
  74637. ear = next.next;
  74638. stop = next.next;
  74639. continue;
  74640. }
  74641. ear = next;
  74642. // if we looped through the whole remaining polygon and can't find any more ears
  74643. if (ear === stop) {
  74644. // try filtering points and slicing again
  74645. if (!pass) {
  74646. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  74647. // if this didn't work, try curing all small self-intersections locally
  74648. }
  74649. else if (pass === 1) {
  74650. ear = cureLocalIntersections(ear, triangles, dim);
  74651. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  74652. // as a last resort, try splitting the remaining polygon into two
  74653. }
  74654. else if (pass === 2) {
  74655. splitEarcut(ear, triangles, dim, minX, minY, size);
  74656. }
  74657. break;
  74658. }
  74659. }
  74660. }
  74661. // check whether a polygon node forms a valid ear with adjacent nodes
  74662. function isEar(ear) {
  74663. var a = ear.prev, b = ear, c = ear.next;
  74664. if (area(a, b, c) >= 0)
  74665. return false; // reflex, can't be an ear
  74666. // now make sure we don't have other points inside the potential ear
  74667. var p = ear.next.next;
  74668. while (p !== ear.prev) {
  74669. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74670. area(p.prev, p, p.next) >= 0)
  74671. return false;
  74672. p = p.next;
  74673. }
  74674. return true;
  74675. }
  74676. function isEarHashed(ear, minX, minY, size) {
  74677. var a = ear.prev, b = ear, c = ear.next;
  74678. if (area(a, b, c) >= 0)
  74679. return false; // reflex, can't be an ear
  74680. // triangle bbox; min & max are calculated like this for speed
  74681. 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);
  74682. // z-order range for the current triangle bbox;
  74683. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  74684. // first look for points inside the triangle in increasing z-order
  74685. var p = ear.nextZ;
  74686. while (p && p.z <= maxZ) {
  74687. if (p !== ear.prev &&
  74688. p !== ear.next &&
  74689. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74690. area(p.prev, p, p.next) >= 0)
  74691. return false;
  74692. p = p.nextZ;
  74693. }
  74694. // then look for points in decreasing z-order
  74695. p = ear.prevZ;
  74696. while (p && p.z >= minZ) {
  74697. if (p !== ear.prev &&
  74698. p !== ear.next &&
  74699. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  74700. area(p.prev, p, p.next) >= 0)
  74701. return false;
  74702. p = p.prevZ;
  74703. }
  74704. return true;
  74705. }
  74706. // go through all polygon nodes and cure small local self-intersections
  74707. function cureLocalIntersections(start, triangles, dim) {
  74708. var p = start;
  74709. do {
  74710. var a = p.prev, b = p.next.next;
  74711. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  74712. triangles.push(a.i / dim);
  74713. triangles.push(p.i / dim);
  74714. triangles.push(b.i / dim);
  74715. // remove two nodes involved
  74716. removeNode(p);
  74717. removeNode(p.next);
  74718. p = start = b;
  74719. }
  74720. p = p.next;
  74721. } while (p !== start);
  74722. return p;
  74723. }
  74724. // try splitting polygon into two and triangulate them independently
  74725. function splitEarcut(start, triangles, dim, minX, minY, size) {
  74726. // look for a valid diagonal that divides the polygon into two
  74727. var a = start;
  74728. do {
  74729. var b = a.next.next;
  74730. while (b !== a.prev) {
  74731. if (a.i !== b.i && isValidDiagonal(a, b)) {
  74732. // split the polygon in two by the diagonal
  74733. var c = splitPolygon(a, b);
  74734. // filter colinear points around the cuts
  74735. a = filterPoints(a, a.next);
  74736. c = filterPoints(c, c.next);
  74737. // run earcut on each half
  74738. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  74739. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  74740. return;
  74741. }
  74742. b = b.next;
  74743. }
  74744. a = a.next;
  74745. } while (a !== start);
  74746. }
  74747. // link every hole into the outer loop, producing a single-ring polygon without holes
  74748. function eliminateHoles(data, holeIndices, outerNode, dim) {
  74749. var queue = [], i, len, start, end, list;
  74750. for (i = 0, len = holeIndices.length; i < len; i++) {
  74751. start = holeIndices[i] * dim;
  74752. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  74753. list = linkedList(data, start, end, dim, false);
  74754. if (list === list.next)
  74755. list.steiner = true;
  74756. queue.push(getLeftmost(list));
  74757. }
  74758. queue.sort(compareX);
  74759. // process holes from left to right
  74760. for (i = 0; i < queue.length; i++) {
  74761. eliminateHole(queue[i], outerNode);
  74762. outerNode = filterPoints(outerNode, outerNode.next);
  74763. }
  74764. return outerNode;
  74765. }
  74766. function compareX(a, b) {
  74767. return a.x - b.x;
  74768. }
  74769. // find a bridge between vertices that connects hole with an outer ring and and link it
  74770. function eliminateHole(hole, outerNode) {
  74771. outerNode = findHoleBridge(hole, outerNode);
  74772. if (outerNode) {
  74773. var b = splitPolygon(outerNode, hole);
  74774. filterPoints(b, b.next);
  74775. }
  74776. }
  74777. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  74778. function findHoleBridge(hole, outerNode) {
  74779. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  74780. // find a segment intersected by a ray from the hole's leftmost point to the left;
  74781. // segment's endpoint with lesser x will be potential connection point
  74782. do {
  74783. if (hy <= p.y && hy >= p.next.y) {
  74784. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  74785. if (x <= hx && x > qx) {
  74786. qx = x;
  74787. if (x === hx) {
  74788. if (hy === p.y)
  74789. return p;
  74790. if (hy === p.next.y)
  74791. return p.next;
  74792. }
  74793. m = p.x < p.next.x ? p : p.next;
  74794. }
  74795. }
  74796. p = p.next;
  74797. } while (p !== outerNode);
  74798. if (!m)
  74799. return null;
  74800. if (hx === qx)
  74801. return m.prev; // hole touches outer segment; pick lower endpoint
  74802. // look for points inside the triangle of hole point, segment intersection and endpoint;
  74803. // if there are no points found, we have a valid connection;
  74804. // otherwise choose the point of the minimum angle with the ray as connection point
  74805. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  74806. p = m.next;
  74807. while (p !== stop) {
  74808. if (hx >= p.x &&
  74809. p.x >= mx &&
  74810. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  74811. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  74812. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  74813. m = p;
  74814. tanMin = tan;
  74815. }
  74816. }
  74817. p = p.next;
  74818. }
  74819. return m;
  74820. }
  74821. // interlink polygon nodes in z-order
  74822. function indexCurve(start, minX, minY, size) {
  74823. var p = start;
  74824. do {
  74825. if (p.z === null)
  74826. p.z = zOrder(p.x, p.y, minX, minY, size);
  74827. p.prevZ = p.prev;
  74828. p.nextZ = p.next;
  74829. p = p.next;
  74830. } while (p !== start);
  74831. p.prevZ.nextZ = null;
  74832. p.prevZ = null;
  74833. sortLinked(p);
  74834. }
  74835. // Simon Tatham's linked list merge sort algorithm
  74836. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  74837. function sortLinked(list) {
  74838. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  74839. do {
  74840. p = list;
  74841. list = null;
  74842. tail = null;
  74843. numMerges = 0;
  74844. while (p) {
  74845. numMerges++;
  74846. q = p;
  74847. pSize = 0;
  74848. for (i = 0; i < inSize; i++) {
  74849. pSize++;
  74850. q = q.nextZ;
  74851. if (!q)
  74852. break;
  74853. }
  74854. qSize = inSize;
  74855. while (pSize > 0 || (qSize > 0 && q)) {
  74856. if (pSize === 0) {
  74857. e = q;
  74858. q = q.nextZ;
  74859. qSize--;
  74860. }
  74861. else if (qSize === 0 || !q) {
  74862. e = p;
  74863. p = p.nextZ;
  74864. pSize--;
  74865. }
  74866. else if (p.z <= q.z) {
  74867. e = p;
  74868. p = p.nextZ;
  74869. pSize--;
  74870. }
  74871. else {
  74872. e = q;
  74873. q = q.nextZ;
  74874. qSize--;
  74875. }
  74876. if (tail)
  74877. tail.nextZ = e;
  74878. else
  74879. list = e;
  74880. e.prevZ = tail;
  74881. tail = e;
  74882. }
  74883. p = q;
  74884. }
  74885. tail.nextZ = null;
  74886. inSize *= 2;
  74887. } while (numMerges > 1);
  74888. return list;
  74889. }
  74890. // z-order of a point given coords and size of the data bounding box
  74891. function zOrder(x, y, minX, minY, size) {
  74892. // coords are transformed into non-negative 15-bit integer range
  74893. x = 32767 * (x - minX) / size;
  74894. y = 32767 * (y - minY) / size;
  74895. x = (x | (x << 8)) & 0x00FF00FF;
  74896. x = (x | (x << 4)) & 0x0F0F0F0F;
  74897. x = (x | (x << 2)) & 0x33333333;
  74898. x = (x | (x << 1)) & 0x55555555;
  74899. y = (y | (y << 8)) & 0x00FF00FF;
  74900. y = (y | (y << 4)) & 0x0F0F0F0F;
  74901. y = (y | (y << 2)) & 0x33333333;
  74902. y = (y | (y << 1)) & 0x55555555;
  74903. return x | (y << 1);
  74904. }
  74905. // find the leftmost node of a polygon ring
  74906. function getLeftmost(start) {
  74907. var p = start, leftmost = start;
  74908. do {
  74909. if (p.x < leftmost.x)
  74910. leftmost = p;
  74911. p = p.next;
  74912. } while (p !== start);
  74913. return leftmost;
  74914. }
  74915. // check if a point lies within a convex triangle
  74916. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  74917. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  74918. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  74919. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  74920. }
  74921. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  74922. function isValidDiagonal(a, b) {
  74923. return a.next.i !== b.i &&
  74924. a.prev.i !== b.i &&
  74925. !intersectsPolygon(a, b) &&
  74926. locallyInside(a, b) &&
  74927. locallyInside(b, a) &&
  74928. middleInside(a, b);
  74929. }
  74930. // signed area of a triangle
  74931. function area(p, q, r) {
  74932. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  74933. }
  74934. // check if two points are equal
  74935. function equals(p1, p2) {
  74936. return p1.x === p2.x && p1.y === p2.y;
  74937. }
  74938. // check if two segments intersect
  74939. function intersects(p1, q1, p2, q2) {
  74940. if ((equals(p1, q1) && equals(p2, q2)) ||
  74941. (equals(p1, q2) && equals(p2, q1)))
  74942. return true;
  74943. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  74944. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  74945. }
  74946. // check if a polygon diagonal intersects any polygon segments
  74947. function intersectsPolygon(a, b) {
  74948. var p = a;
  74949. do {
  74950. if (p.i !== a.i &&
  74951. p.next.i !== a.i &&
  74952. p.i !== b.i &&
  74953. p.next.i !== b.i &&
  74954. intersects(p, p.next, a, b))
  74955. return true;
  74956. p = p.next;
  74957. } while (p !== a);
  74958. return false;
  74959. }
  74960. // check if a polygon diagonal is locally inside the polygon
  74961. function locallyInside(a, b) {
  74962. return area(a.prev, a, a.next) < 0
  74963. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  74964. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  74965. }
  74966. // check if the middle point of a polygon diagonal is inside the polygon
  74967. function middleInside(a, b) {
  74968. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  74969. do {
  74970. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  74971. inside = !inside;
  74972. p = p.next;
  74973. } while (p !== a);
  74974. return inside;
  74975. }
  74976. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  74977. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  74978. function splitPolygon(a, b) {
  74979. 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;
  74980. a.next = b;
  74981. b.prev = a;
  74982. a2.next = an;
  74983. an.prev = a2;
  74984. b2.next = a2;
  74985. a2.prev = b2;
  74986. bp.next = b2;
  74987. b2.prev = bp;
  74988. return b2;
  74989. }
  74990. // create a node and optionally link it with previous one (in a circular doubly linked list)
  74991. function insertNode(i, x, y, last) {
  74992. var p = new Node(i, x, y);
  74993. if (!last) {
  74994. p.prev = p;
  74995. p.next = p;
  74996. }
  74997. else {
  74998. p.next = last.next;
  74999. p.prev = last;
  75000. last.next.prev = p;
  75001. last.next = p;
  75002. }
  75003. return p;
  75004. }
  75005. function removeNode(p) {
  75006. p.next.prev = p.prev;
  75007. p.prev.next = p.next;
  75008. if (p.prevZ)
  75009. p.prevZ.nextZ = p.nextZ;
  75010. if (p.nextZ)
  75011. p.nextZ.prevZ = p.prevZ;
  75012. }
  75013. /**
  75014. * return a percentage difference between the polygon area and its triangulation area;
  75015. * used to verify correctness of triangulation
  75016. */
  75017. function deviation(data, holeIndices, dim, triangles) {
  75018. var hasHoles = holeIndices && holeIndices.length;
  75019. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  75020. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  75021. if (hasHoles) {
  75022. for (var i = 0, len = holeIndices.length; i < len; i++) {
  75023. var start = holeIndices[i] * dim;
  75024. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75025. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  75026. }
  75027. }
  75028. var trianglesArea = 0;
  75029. for (i = 0; i < triangles.length; i += 3) {
  75030. var a = triangles[i] * dim;
  75031. var b = triangles[i + 1] * dim;
  75032. var c = triangles[i + 2] * dim;
  75033. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  75034. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  75035. }
  75036. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  75037. }
  75038. Earcut.deviation = deviation;
  75039. ;
  75040. function signedArea(data, start, end, dim) {
  75041. var sum = 0;
  75042. for (var i = start, j = end - dim; i < end; i += dim) {
  75043. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  75044. j = i;
  75045. }
  75046. return sum;
  75047. }
  75048. /**
  75049. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  75050. */
  75051. function flatten(data) {
  75052. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  75053. for (var i = 0; i < data.length; i++) {
  75054. for (var j = 0; j < data[i].length; j++) {
  75055. for (var d = 0; d < dim; d++)
  75056. result.vertices.push(data[i][j][d]);
  75057. }
  75058. if (i > 0) {
  75059. holeIndex += data[i - 1].length;
  75060. result.holes.push(holeIndex);
  75061. }
  75062. }
  75063. return result;
  75064. }
  75065. Earcut.flatten = flatten;
  75066. ;
  75067. })(Earcut || (Earcut = {}));
  75068. //# sourceMappingURL=babylon.earcut.js.map
  75069. "use strict";
  75070. var BABYLON;
  75071. (function (BABYLON) {
  75072. var IndexedVector2 = /** @class */ (function (_super) {
  75073. __extends(IndexedVector2, _super);
  75074. function IndexedVector2(original, index) {
  75075. var _this = _super.call(this, original.x, original.y) || this;
  75076. _this.index = index;
  75077. return _this;
  75078. }
  75079. return IndexedVector2;
  75080. }(BABYLON.Vector2));
  75081. var PolygonPoints = /** @class */ (function () {
  75082. function PolygonPoints() {
  75083. this.elements = new Array();
  75084. }
  75085. PolygonPoints.prototype.add = function (originalPoints) {
  75086. var _this = this;
  75087. var result = new Array();
  75088. originalPoints.forEach(function (point) {
  75089. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  75090. var newPoint = new IndexedVector2(point, _this.elements.length);
  75091. result.push(newPoint);
  75092. _this.elements.push(newPoint);
  75093. }
  75094. });
  75095. return result;
  75096. };
  75097. PolygonPoints.prototype.computeBounds = function () {
  75098. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75099. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75100. this.elements.forEach(function (point) {
  75101. // x
  75102. if (point.x < lmin.x) {
  75103. lmin.x = point.x;
  75104. }
  75105. else if (point.x > lmax.x) {
  75106. lmax.x = point.x;
  75107. }
  75108. // y
  75109. if (point.y < lmin.y) {
  75110. lmin.y = point.y;
  75111. }
  75112. else if (point.y > lmax.y) {
  75113. lmax.y = point.y;
  75114. }
  75115. });
  75116. return {
  75117. min: lmin,
  75118. max: lmax,
  75119. width: lmax.x - lmin.x,
  75120. height: lmax.y - lmin.y
  75121. };
  75122. };
  75123. return PolygonPoints;
  75124. }());
  75125. var Polygon = /** @class */ (function () {
  75126. function Polygon() {
  75127. }
  75128. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  75129. return [
  75130. new BABYLON.Vector2(xmin, ymin),
  75131. new BABYLON.Vector2(xmax, ymin),
  75132. new BABYLON.Vector2(xmax, ymax),
  75133. new BABYLON.Vector2(xmin, ymax)
  75134. ];
  75135. };
  75136. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  75137. if (cx === void 0) { cx = 0; }
  75138. if (cy === void 0) { cy = 0; }
  75139. if (numberOfSides === void 0) { numberOfSides = 32; }
  75140. var result = new Array();
  75141. var angle = 0;
  75142. var increment = (Math.PI * 2) / numberOfSides;
  75143. for (var i = 0; i < numberOfSides; i++) {
  75144. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75145. angle -= increment;
  75146. }
  75147. return result;
  75148. };
  75149. Polygon.Parse = function (input) {
  75150. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75151. var i, result = [];
  75152. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75153. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75154. }
  75155. return result;
  75156. };
  75157. Polygon.StartingAt = function (x, y) {
  75158. return BABYLON.Path2.StartingAt(x, y);
  75159. };
  75160. return Polygon;
  75161. }());
  75162. BABYLON.Polygon = Polygon;
  75163. var PolygonMeshBuilder = /** @class */ (function () {
  75164. function PolygonMeshBuilder(name, contours, scene) {
  75165. this._points = new PolygonPoints();
  75166. this._outlinepoints = new PolygonPoints();
  75167. this._holes = new Array();
  75168. this._epoints = new Array();
  75169. this._eholes = new Array();
  75170. this._name = name;
  75171. this._scene = scene;
  75172. var points;
  75173. if (contours instanceof BABYLON.Path2) {
  75174. points = contours.getPoints();
  75175. }
  75176. else {
  75177. points = contours;
  75178. }
  75179. this._addToepoint(points);
  75180. this._points.add(points);
  75181. this._outlinepoints.add(points);
  75182. }
  75183. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75184. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75185. var p = points_1[_i];
  75186. this._epoints.push(p.x, p.y);
  75187. }
  75188. };
  75189. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75190. this._points.add(hole);
  75191. var holepoints = new PolygonPoints();
  75192. holepoints.add(hole);
  75193. this._holes.push(holepoints);
  75194. this._eholes.push(this._epoints.length / 2);
  75195. this._addToepoint(hole);
  75196. return this;
  75197. };
  75198. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75199. var _this = this;
  75200. if (updatable === void 0) { updatable = false; }
  75201. if (depth === void 0) { depth = 0; }
  75202. var result = new BABYLON.Mesh(this._name, this._scene);
  75203. var normals = new Array();
  75204. var positions = new Array();
  75205. var uvs = new Array();
  75206. var bounds = this._points.computeBounds();
  75207. this._points.elements.forEach(function (p) {
  75208. normals.push(0, 1.0, 0);
  75209. positions.push(p.x, 0, p.y);
  75210. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75211. });
  75212. var indices = new Array();
  75213. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  75214. for (var i = 0; i < res.length; i++) {
  75215. indices.push(res[i]);
  75216. }
  75217. if (depth > 0) {
  75218. var positionscount = (positions.length / 3); //get the current pointcount
  75219. this._points.elements.forEach(function (p) {
  75220. normals.push(0, -1.0, 0);
  75221. positions.push(p.x, -depth, p.y);
  75222. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  75223. });
  75224. var totalCount = indices.length;
  75225. for (var i = 0; i < totalCount; i += 3) {
  75226. var i0 = indices[i + 0];
  75227. var i1 = indices[i + 1];
  75228. var i2 = indices[i + 2];
  75229. indices.push(i2 + positionscount);
  75230. indices.push(i1 + positionscount);
  75231. indices.push(i0 + positionscount);
  75232. }
  75233. //Add the sides
  75234. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  75235. this._holes.forEach(function (hole) {
  75236. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  75237. });
  75238. }
  75239. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  75240. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  75241. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  75242. result.setIndices(indices);
  75243. return result;
  75244. };
  75245. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  75246. var StartIndex = positions.length / 3;
  75247. var ulength = 0;
  75248. for (var i = 0; i < points.elements.length; i++) {
  75249. var p = points.elements[i];
  75250. var p1;
  75251. if ((i + 1) > points.elements.length - 1) {
  75252. p1 = points.elements[0];
  75253. }
  75254. else {
  75255. p1 = points.elements[i + 1];
  75256. }
  75257. positions.push(p.x, 0, p.y);
  75258. positions.push(p.x, -depth, p.y);
  75259. positions.push(p1.x, 0, p1.y);
  75260. positions.push(p1.x, -depth, p1.y);
  75261. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  75262. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  75263. var v3 = v2.subtract(v1);
  75264. var v4 = new BABYLON.Vector3(0, 1, 0);
  75265. var vn = BABYLON.Vector3.Cross(v3, v4);
  75266. vn = vn.normalize();
  75267. uvs.push(ulength / bounds.width, 0);
  75268. uvs.push(ulength / bounds.width, 1);
  75269. ulength += v3.length();
  75270. uvs.push((ulength / bounds.width), 0);
  75271. uvs.push((ulength / bounds.width), 1);
  75272. if (!flip) {
  75273. normals.push(-vn.x, -vn.y, -vn.z);
  75274. normals.push(-vn.x, -vn.y, -vn.z);
  75275. normals.push(-vn.x, -vn.y, -vn.z);
  75276. normals.push(-vn.x, -vn.y, -vn.z);
  75277. indices.push(StartIndex);
  75278. indices.push(StartIndex + 1);
  75279. indices.push(StartIndex + 2);
  75280. indices.push(StartIndex + 1);
  75281. indices.push(StartIndex + 3);
  75282. indices.push(StartIndex + 2);
  75283. }
  75284. else {
  75285. normals.push(vn.x, vn.y, vn.z);
  75286. normals.push(vn.x, vn.y, vn.z);
  75287. normals.push(vn.x, vn.y, vn.z);
  75288. normals.push(vn.x, vn.y, vn.z);
  75289. indices.push(StartIndex);
  75290. indices.push(StartIndex + 2);
  75291. indices.push(StartIndex + 1);
  75292. indices.push(StartIndex + 1);
  75293. indices.push(StartIndex + 2);
  75294. indices.push(StartIndex + 3);
  75295. }
  75296. StartIndex += 4;
  75297. }
  75298. ;
  75299. };
  75300. return PolygonMeshBuilder;
  75301. }());
  75302. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  75303. })(BABYLON || (BABYLON = {}));
  75304. //# sourceMappingURL=babylon.polygonMesh.js.map
  75305. "use strict";
  75306. var BABYLON;
  75307. (function (BABYLON) {
  75308. // Unique ID when we import meshes from Babylon to CSG
  75309. var currentCSGMeshId = 0;
  75310. // # class Vertex
  75311. // Represents a vertex of a polygon. Use your own vertex class instead of this
  75312. // one to provide additional features like texture coordinates and vertex
  75313. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  75314. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  75315. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  75316. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  75317. // is not used anywhere else.
  75318. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  75319. var Vertex = /** @class */ (function () {
  75320. function Vertex(pos, normal, uv) {
  75321. this.pos = pos;
  75322. this.normal = normal;
  75323. this.uv = uv;
  75324. }
  75325. Vertex.prototype.clone = function () {
  75326. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  75327. };
  75328. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  75329. // orientation of a polygon is flipped.
  75330. Vertex.prototype.flip = function () {
  75331. this.normal = this.normal.scale(-1);
  75332. };
  75333. // Create a new vertex between this vertex and `other` by linearly
  75334. // interpolating all properties using a parameter of `t`. Subclasses should
  75335. // override this to interpolate additional properties.
  75336. Vertex.prototype.interpolate = function (other, t) {
  75337. 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));
  75338. };
  75339. return Vertex;
  75340. }());
  75341. // # class Plane
  75342. // Represents a plane in 3D space.
  75343. var Plane = /** @class */ (function () {
  75344. function Plane(normal, w) {
  75345. this.normal = normal;
  75346. this.w = w;
  75347. }
  75348. Plane.FromPoints = function (a, b, c) {
  75349. var v0 = c.subtract(a);
  75350. var v1 = b.subtract(a);
  75351. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  75352. return null;
  75353. }
  75354. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  75355. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  75356. };
  75357. Plane.prototype.clone = function () {
  75358. return new Plane(this.normal.clone(), this.w);
  75359. };
  75360. Plane.prototype.flip = function () {
  75361. this.normal.scaleInPlace(-1);
  75362. this.w = -this.w;
  75363. };
  75364. // Split `polygon` by this plane if needed, then put the polygon or polygon
  75365. // fragments in the appropriate lists. Coplanar polygons go into either
  75366. // `coplanarFront` or `coplanarBack` depending on their orientation with
  75367. // respect to this plane. Polygons in front or in back of this plane go into
  75368. // either `front` or `back`.
  75369. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  75370. var COPLANAR = 0;
  75371. var FRONT = 1;
  75372. var BACK = 2;
  75373. var SPANNING = 3;
  75374. // Classify each point as well as the entire polygon into one of the above
  75375. // four classes.
  75376. var polygonType = 0;
  75377. var types = [];
  75378. var i;
  75379. var t;
  75380. for (i = 0; i < polygon.vertices.length; i++) {
  75381. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  75382. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  75383. polygonType |= type;
  75384. types.push(type);
  75385. }
  75386. // Put the polygon in the correct list, splitting it when necessary.
  75387. switch (polygonType) {
  75388. case COPLANAR:
  75389. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  75390. break;
  75391. case FRONT:
  75392. front.push(polygon);
  75393. break;
  75394. case BACK:
  75395. back.push(polygon);
  75396. break;
  75397. case SPANNING:
  75398. var f = [], b = [];
  75399. for (i = 0; i < polygon.vertices.length; i++) {
  75400. var j = (i + 1) % polygon.vertices.length;
  75401. var ti = types[i], tj = types[j];
  75402. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  75403. if (ti !== BACK)
  75404. f.push(vi);
  75405. if (ti !== FRONT)
  75406. b.push(ti !== BACK ? vi.clone() : vi);
  75407. if ((ti | tj) === SPANNING) {
  75408. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  75409. var v = vi.interpolate(vj, t);
  75410. f.push(v);
  75411. b.push(v.clone());
  75412. }
  75413. }
  75414. var poly;
  75415. if (f.length >= 3) {
  75416. poly = new Polygon(f, polygon.shared);
  75417. if (poly.plane)
  75418. front.push(poly);
  75419. }
  75420. if (b.length >= 3) {
  75421. poly = new Polygon(b, polygon.shared);
  75422. if (poly.plane)
  75423. back.push(poly);
  75424. }
  75425. break;
  75426. }
  75427. };
  75428. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  75429. // point is on the plane.
  75430. Plane.EPSILON = 1e-5;
  75431. return Plane;
  75432. }());
  75433. // # class Polygon
  75434. // Represents a convex polygon. The vertices used to initialize a polygon must
  75435. // be coplanar and form a convex loop.
  75436. //
  75437. // Each convex polygon has a `shared` property, which is shared between all
  75438. // polygons that are clones of each other or were split from the same polygon.
  75439. // This can be used to define per-polygon properties (such as surface color).
  75440. var Polygon = /** @class */ (function () {
  75441. function Polygon(vertices, shared) {
  75442. this.vertices = vertices;
  75443. this.shared = shared;
  75444. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  75445. }
  75446. Polygon.prototype.clone = function () {
  75447. var vertices = this.vertices.map(function (v) { return v.clone(); });
  75448. return new Polygon(vertices, this.shared);
  75449. };
  75450. Polygon.prototype.flip = function () {
  75451. this.vertices.reverse().map(function (v) { v.flip(); });
  75452. this.plane.flip();
  75453. };
  75454. return Polygon;
  75455. }());
  75456. // # class Node
  75457. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  75458. // by picking a polygon to split along. That polygon (and all other coplanar
  75459. // polygons) are added directly to that node and the other polygons are added to
  75460. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  75461. // no distinction between internal and leaf nodes.
  75462. var Node = /** @class */ (function () {
  75463. function Node(polygons) {
  75464. this.plane = null;
  75465. this.front = null;
  75466. this.back = null;
  75467. this.polygons = new Array();
  75468. if (polygons) {
  75469. this.build(polygons);
  75470. }
  75471. }
  75472. Node.prototype.clone = function () {
  75473. var node = new Node();
  75474. node.plane = this.plane && this.plane.clone();
  75475. node.front = this.front && this.front.clone();
  75476. node.back = this.back && this.back.clone();
  75477. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  75478. return node;
  75479. };
  75480. // Convert solid space to empty space and empty space to solid space.
  75481. Node.prototype.invert = function () {
  75482. for (var i = 0; i < this.polygons.length; i++) {
  75483. this.polygons[i].flip();
  75484. }
  75485. if (this.plane) {
  75486. this.plane.flip();
  75487. }
  75488. if (this.front) {
  75489. this.front.invert();
  75490. }
  75491. if (this.back) {
  75492. this.back.invert();
  75493. }
  75494. var temp = this.front;
  75495. this.front = this.back;
  75496. this.back = temp;
  75497. };
  75498. // Recursively remove all polygons in `polygons` that are inside this BSP
  75499. // tree.
  75500. Node.prototype.clipPolygons = function (polygons) {
  75501. if (!this.plane)
  75502. return polygons.slice();
  75503. var front = new Array(), back = new Array();
  75504. for (var i = 0; i < polygons.length; i++) {
  75505. this.plane.splitPolygon(polygons[i], front, back, front, back);
  75506. }
  75507. if (this.front) {
  75508. front = this.front.clipPolygons(front);
  75509. }
  75510. if (this.back) {
  75511. back = this.back.clipPolygons(back);
  75512. }
  75513. else {
  75514. back = [];
  75515. }
  75516. return front.concat(back);
  75517. };
  75518. // Remove all polygons in this BSP tree that are inside the other BSP tree
  75519. // `bsp`.
  75520. Node.prototype.clipTo = function (bsp) {
  75521. this.polygons = bsp.clipPolygons(this.polygons);
  75522. if (this.front)
  75523. this.front.clipTo(bsp);
  75524. if (this.back)
  75525. this.back.clipTo(bsp);
  75526. };
  75527. // Return a list of all polygons in this BSP tree.
  75528. Node.prototype.allPolygons = function () {
  75529. var polygons = this.polygons.slice();
  75530. if (this.front)
  75531. polygons = polygons.concat(this.front.allPolygons());
  75532. if (this.back)
  75533. polygons = polygons.concat(this.back.allPolygons());
  75534. return polygons;
  75535. };
  75536. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  75537. // new polygons are filtered down to the bottom of the tree and become new
  75538. // nodes there. Each set of polygons is partitioned using the first polygon
  75539. // (no heuristic is used to pick a good split).
  75540. Node.prototype.build = function (polygons) {
  75541. if (!polygons.length)
  75542. return;
  75543. if (!this.plane)
  75544. this.plane = polygons[0].plane.clone();
  75545. var front = new Array(), back = new Array();
  75546. for (var i = 0; i < polygons.length; i++) {
  75547. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  75548. }
  75549. if (front.length) {
  75550. if (!this.front)
  75551. this.front = new Node();
  75552. this.front.build(front);
  75553. }
  75554. if (back.length) {
  75555. if (!this.back)
  75556. this.back = new Node();
  75557. this.back.build(back);
  75558. }
  75559. };
  75560. return Node;
  75561. }());
  75562. var CSG = /** @class */ (function () {
  75563. function CSG() {
  75564. this.polygons = new Array();
  75565. }
  75566. // Convert BABYLON.Mesh to BABYLON.CSG
  75567. CSG.FromMesh = function (mesh) {
  75568. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  75569. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  75570. if (mesh instanceof BABYLON.Mesh) {
  75571. mesh.computeWorldMatrix(true);
  75572. matrix = mesh.getWorldMatrix();
  75573. meshPosition = mesh.position.clone();
  75574. meshRotation = mesh.rotation.clone();
  75575. if (mesh.rotationQuaternion) {
  75576. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  75577. }
  75578. meshScaling = mesh.scaling.clone();
  75579. }
  75580. else {
  75581. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  75582. }
  75583. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75584. var subMeshes = mesh.subMeshes;
  75585. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  75586. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  75587. vertices = [];
  75588. for (var j = 0; j < 3; j++) {
  75589. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  75590. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  75591. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  75592. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  75593. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  75594. vertex = new Vertex(position, normal, uv);
  75595. vertices.push(vertex);
  75596. }
  75597. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  75598. // To handle the case of degenerated triangle
  75599. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  75600. if (polygon.plane)
  75601. polygons.push(polygon);
  75602. }
  75603. }
  75604. var csg = CSG.FromPolygons(polygons);
  75605. csg.matrix = matrix;
  75606. csg.position = meshPosition;
  75607. csg.rotation = meshRotation;
  75608. csg.scaling = meshScaling;
  75609. csg.rotationQuaternion = meshRotationQuaternion;
  75610. currentCSGMeshId++;
  75611. return csg;
  75612. };
  75613. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  75614. CSG.FromPolygons = function (polygons) {
  75615. var csg = new CSG();
  75616. csg.polygons = polygons;
  75617. return csg;
  75618. };
  75619. CSG.prototype.clone = function () {
  75620. var csg = new CSG();
  75621. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  75622. csg.copyTransformAttributes(this);
  75623. return csg;
  75624. };
  75625. CSG.prototype.union = function (csg) {
  75626. var a = new Node(this.clone().polygons);
  75627. var b = new Node(csg.clone().polygons);
  75628. a.clipTo(b);
  75629. b.clipTo(a);
  75630. b.invert();
  75631. b.clipTo(a);
  75632. b.invert();
  75633. a.build(b.allPolygons());
  75634. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75635. };
  75636. CSG.prototype.unionInPlace = function (csg) {
  75637. var a = new Node(this.polygons);
  75638. var b = new Node(csg.polygons);
  75639. a.clipTo(b);
  75640. b.clipTo(a);
  75641. b.invert();
  75642. b.clipTo(a);
  75643. b.invert();
  75644. a.build(b.allPolygons());
  75645. this.polygons = a.allPolygons();
  75646. };
  75647. CSG.prototype.subtract = function (csg) {
  75648. var a = new Node(this.clone().polygons);
  75649. var b = new Node(csg.clone().polygons);
  75650. a.invert();
  75651. a.clipTo(b);
  75652. b.clipTo(a);
  75653. b.invert();
  75654. b.clipTo(a);
  75655. b.invert();
  75656. a.build(b.allPolygons());
  75657. a.invert();
  75658. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75659. };
  75660. CSG.prototype.subtractInPlace = function (csg) {
  75661. var a = new Node(this.polygons);
  75662. var b = new Node(csg.polygons);
  75663. a.invert();
  75664. a.clipTo(b);
  75665. b.clipTo(a);
  75666. b.invert();
  75667. b.clipTo(a);
  75668. b.invert();
  75669. a.build(b.allPolygons());
  75670. a.invert();
  75671. this.polygons = a.allPolygons();
  75672. };
  75673. CSG.prototype.intersect = function (csg) {
  75674. var a = new Node(this.clone().polygons);
  75675. var b = new Node(csg.clone().polygons);
  75676. a.invert();
  75677. b.clipTo(a);
  75678. b.invert();
  75679. a.clipTo(b);
  75680. b.clipTo(a);
  75681. a.build(b.allPolygons());
  75682. a.invert();
  75683. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  75684. };
  75685. CSG.prototype.intersectInPlace = function (csg) {
  75686. var a = new Node(this.polygons);
  75687. var b = new Node(csg.polygons);
  75688. a.invert();
  75689. b.clipTo(a);
  75690. b.invert();
  75691. a.clipTo(b);
  75692. b.clipTo(a);
  75693. a.build(b.allPolygons());
  75694. a.invert();
  75695. this.polygons = a.allPolygons();
  75696. };
  75697. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  75698. // not modified.
  75699. CSG.prototype.inverse = function () {
  75700. var csg = this.clone();
  75701. csg.inverseInPlace();
  75702. return csg;
  75703. };
  75704. CSG.prototype.inverseInPlace = function () {
  75705. this.polygons.map(function (p) { p.flip(); });
  75706. };
  75707. // This is used to keep meshes transformations so they can be restored
  75708. // when we build back a Babylon Mesh
  75709. // NB : All CSG operations are performed in world coordinates
  75710. CSG.prototype.copyTransformAttributes = function (csg) {
  75711. this.matrix = csg.matrix;
  75712. this.position = csg.position;
  75713. this.rotation = csg.rotation;
  75714. this.scaling = csg.scaling;
  75715. this.rotationQuaternion = csg.rotationQuaternion;
  75716. return this;
  75717. };
  75718. // Build Raw mesh from CSG
  75719. // Coordinates here are in world space
  75720. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  75721. var matrix = this.matrix.clone();
  75722. matrix.invert();
  75723. 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;
  75724. if (keepSubMeshes) {
  75725. // Sort Polygons, since subMeshes are indices range
  75726. polygons.sort(function (a, b) {
  75727. if (a.shared.meshId === b.shared.meshId) {
  75728. return a.shared.subMeshId - b.shared.subMeshId;
  75729. }
  75730. else {
  75731. return a.shared.meshId - b.shared.meshId;
  75732. }
  75733. });
  75734. }
  75735. for (var i = 0, il = polygons.length; i < il; i++) {
  75736. polygon = polygons[i];
  75737. // Building SubMeshes
  75738. if (!subMesh_dict[polygon.shared.meshId]) {
  75739. subMesh_dict[polygon.shared.meshId] = {};
  75740. }
  75741. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  75742. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  75743. indexStart: +Infinity,
  75744. indexEnd: -Infinity,
  75745. materialIndex: polygon.shared.materialIndex
  75746. };
  75747. }
  75748. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  75749. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  75750. polygonIndices[0] = 0;
  75751. polygonIndices[1] = j - 1;
  75752. polygonIndices[2] = j;
  75753. for (var k = 0; k < 3; k++) {
  75754. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  75755. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  75756. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  75757. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  75758. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  75759. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  75760. // Check if 2 points can be merged
  75761. if (!(typeof vertex_idx !== 'undefined' &&
  75762. normals[vertex_idx * 3] === localNormal.x &&
  75763. normals[vertex_idx * 3 + 1] === localNormal.y &&
  75764. normals[vertex_idx * 3 + 2] === localNormal.z &&
  75765. uvs[vertex_idx * 2] === uv.x &&
  75766. uvs[vertex_idx * 2 + 1] === uv.y)) {
  75767. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  75768. uvs.push(uv.x, uv.y);
  75769. normals.push(normal.x, normal.y, normal.z);
  75770. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  75771. }
  75772. indices.push(vertex_idx);
  75773. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  75774. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  75775. currentIndex++;
  75776. }
  75777. }
  75778. }
  75779. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  75780. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  75781. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  75782. mesh.setIndices(indices, null);
  75783. if (keepSubMeshes) {
  75784. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  75785. var materialIndexOffset = 0, materialMaxIndex;
  75786. mesh.subMeshes = new Array();
  75787. for (var m in subMesh_dict) {
  75788. materialMaxIndex = -1;
  75789. for (var sm in subMesh_dict[m]) {
  75790. subMesh_obj = subMesh_dict[m][sm];
  75791. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  75792. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  75793. }
  75794. materialIndexOffset += ++materialMaxIndex;
  75795. }
  75796. }
  75797. return mesh;
  75798. };
  75799. // Build Mesh from CSG taking material and transforms into account
  75800. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  75801. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  75802. mesh.material = material;
  75803. mesh.position.copyFrom(this.position);
  75804. mesh.rotation.copyFrom(this.rotation);
  75805. if (this.rotationQuaternion) {
  75806. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  75807. }
  75808. mesh.scaling.copyFrom(this.scaling);
  75809. mesh.computeWorldMatrix(true);
  75810. return mesh;
  75811. };
  75812. return CSG;
  75813. }());
  75814. BABYLON.CSG = CSG;
  75815. })(BABYLON || (BABYLON = {}));
  75816. //# sourceMappingURL=babylon.csg.js.map
  75817. "use strict";
  75818. var BABYLON;
  75819. (function (BABYLON) {
  75820. var LensFlare = /** @class */ (function () {
  75821. function LensFlare(size, position, color, imgUrl, system) {
  75822. this.size = size;
  75823. this.position = position;
  75824. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  75825. this.color = color || new BABYLON.Color3(1, 1, 1);
  75826. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  75827. this._system = system;
  75828. system.lensFlares.push(this);
  75829. }
  75830. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  75831. return new LensFlare(size, position, color, imgUrl, system);
  75832. };
  75833. LensFlare.prototype.dispose = function () {
  75834. if (this.texture) {
  75835. this.texture.dispose();
  75836. }
  75837. // Remove from scene
  75838. var index = this._system.lensFlares.indexOf(this);
  75839. this._system.lensFlares.splice(index, 1);
  75840. };
  75841. ;
  75842. return LensFlare;
  75843. }());
  75844. BABYLON.LensFlare = LensFlare;
  75845. })(BABYLON || (BABYLON = {}));
  75846. //# sourceMappingURL=babylon.lensFlare.js.map
  75847. "use strict";
  75848. var BABYLON;
  75849. (function (BABYLON) {
  75850. var LensFlareSystem = /** @class */ (function () {
  75851. function LensFlareSystem(name, emitter, scene) {
  75852. this.name = name;
  75853. this.lensFlares = new Array();
  75854. this.borderLimit = 300;
  75855. this.viewportBorder = 0;
  75856. this.layerMask = 0x0FFFFFFF;
  75857. this._vertexBuffers = {};
  75858. this._isEnabled = true;
  75859. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75860. this._emitter = emitter;
  75861. this.id = name;
  75862. scene.lensFlareSystems.push(this);
  75863. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  75864. var engine = scene.getEngine();
  75865. // VBO
  75866. var vertices = [];
  75867. vertices.push(1, 1);
  75868. vertices.push(-1, 1);
  75869. vertices.push(-1, -1);
  75870. vertices.push(1, -1);
  75871. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75872. // Indices
  75873. var indices = [];
  75874. indices.push(0);
  75875. indices.push(1);
  75876. indices.push(2);
  75877. indices.push(0);
  75878. indices.push(2);
  75879. indices.push(3);
  75880. this._indexBuffer = engine.createIndexBuffer(indices);
  75881. // Effects
  75882. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  75883. }
  75884. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  75885. get: function () {
  75886. return this._isEnabled;
  75887. },
  75888. set: function (value) {
  75889. this._isEnabled = value;
  75890. },
  75891. enumerable: true,
  75892. configurable: true
  75893. });
  75894. LensFlareSystem.prototype.getScene = function () {
  75895. return this._scene;
  75896. };
  75897. LensFlareSystem.prototype.getEmitter = function () {
  75898. return this._emitter;
  75899. };
  75900. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  75901. this._emitter = newEmitter;
  75902. };
  75903. LensFlareSystem.prototype.getEmitterPosition = function () {
  75904. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  75905. };
  75906. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  75907. var position = this.getEmitterPosition();
  75908. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  75909. this._positionX = position.x;
  75910. this._positionY = position.y;
  75911. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  75912. if (this.viewportBorder > 0) {
  75913. globalViewport.x -= this.viewportBorder;
  75914. globalViewport.y -= this.viewportBorder;
  75915. globalViewport.width += this.viewportBorder * 2;
  75916. globalViewport.height += this.viewportBorder * 2;
  75917. position.x += this.viewportBorder;
  75918. position.y += this.viewportBorder;
  75919. this._positionX += this.viewportBorder;
  75920. this._positionY += this.viewportBorder;
  75921. }
  75922. if (position.z > 0) {
  75923. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  75924. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  75925. return true;
  75926. }
  75927. return true;
  75928. }
  75929. return false;
  75930. };
  75931. LensFlareSystem.prototype._isVisible = function () {
  75932. if (!this._isEnabled || !this._scene.activeCamera) {
  75933. return false;
  75934. }
  75935. var emitterPosition = this.getEmitterPosition();
  75936. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  75937. var distance = direction.length();
  75938. direction.normalize();
  75939. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  75940. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  75941. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  75942. };
  75943. LensFlareSystem.prototype.render = function () {
  75944. if (!this._effect.isReady() || !this._scene.activeCamera)
  75945. return false;
  75946. var engine = this._scene.getEngine();
  75947. var viewport = this._scene.activeCamera.viewport;
  75948. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  75949. // Position
  75950. if (!this.computeEffectivePosition(globalViewport)) {
  75951. return false;
  75952. }
  75953. // Visibility
  75954. if (!this._isVisible()) {
  75955. return false;
  75956. }
  75957. // Intensity
  75958. var awayX;
  75959. var awayY;
  75960. if (this._positionX < this.borderLimit + globalViewport.x) {
  75961. awayX = this.borderLimit + globalViewport.x - this._positionX;
  75962. }
  75963. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  75964. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  75965. }
  75966. else {
  75967. awayX = 0;
  75968. }
  75969. if (this._positionY < this.borderLimit + globalViewport.y) {
  75970. awayY = this.borderLimit + globalViewport.y - this._positionY;
  75971. }
  75972. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  75973. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  75974. }
  75975. else {
  75976. awayY = 0;
  75977. }
  75978. var away = (awayX > awayY) ? awayX : awayY;
  75979. away -= this.viewportBorder;
  75980. if (away > this.borderLimit) {
  75981. away = this.borderLimit;
  75982. }
  75983. var intensity = 1.0 - (away / this.borderLimit);
  75984. if (intensity < 0) {
  75985. return false;
  75986. }
  75987. if (intensity > 1.0) {
  75988. intensity = 1.0;
  75989. }
  75990. if (this.viewportBorder > 0) {
  75991. globalViewport.x += this.viewportBorder;
  75992. globalViewport.y += this.viewportBorder;
  75993. globalViewport.width -= this.viewportBorder * 2;
  75994. globalViewport.height -= this.viewportBorder * 2;
  75995. this._positionX -= this.viewportBorder;
  75996. this._positionY -= this.viewportBorder;
  75997. }
  75998. // Position
  75999. var centerX = globalViewport.x + globalViewport.width / 2;
  76000. var centerY = globalViewport.y + globalViewport.height / 2;
  76001. var distX = centerX - this._positionX;
  76002. var distY = centerY - this._positionY;
  76003. // Effects
  76004. engine.enableEffect(this._effect);
  76005. engine.setState(false);
  76006. engine.setDepthBuffer(false);
  76007. // VBOs
  76008. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76009. // Flares
  76010. for (var index = 0; index < this.lensFlares.length; index++) {
  76011. var flare = this.lensFlares[index];
  76012. engine.setAlphaMode(flare.alphaMode);
  76013. var x = centerX - (distX * flare.position);
  76014. var y = centerY - (distY * flare.position);
  76015. var cw = flare.size;
  76016. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  76017. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  76018. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  76019. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  76020. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  76021. // Texture
  76022. this._effect.setTexture("textureSampler", flare.texture);
  76023. // Color
  76024. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  76025. // Draw order
  76026. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76027. }
  76028. engine.setDepthBuffer(true);
  76029. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76030. return true;
  76031. };
  76032. LensFlareSystem.prototype.dispose = function () {
  76033. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76034. if (vertexBuffer) {
  76035. vertexBuffer.dispose();
  76036. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76037. }
  76038. if (this._indexBuffer) {
  76039. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76040. this._indexBuffer = null;
  76041. }
  76042. while (this.lensFlares.length) {
  76043. this.lensFlares[0].dispose();
  76044. }
  76045. // Remove from scene
  76046. var index = this._scene.lensFlareSystems.indexOf(this);
  76047. this._scene.lensFlareSystems.splice(index, 1);
  76048. };
  76049. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  76050. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  76051. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  76052. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  76053. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  76054. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  76055. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  76056. var parsedFlare = parsedLensFlareSystem.flares[index];
  76057. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  76058. }
  76059. return lensFlareSystem;
  76060. };
  76061. LensFlareSystem.prototype.serialize = function () {
  76062. var serializationObject = {};
  76063. serializationObject.id = this.id;
  76064. serializationObject.name = this.name;
  76065. serializationObject.emitterId = this.getEmitter().id;
  76066. serializationObject.borderLimit = this.borderLimit;
  76067. serializationObject.flares = [];
  76068. for (var index = 0; index < this.lensFlares.length; index++) {
  76069. var flare = this.lensFlares[index];
  76070. serializationObject.flares.push({
  76071. size: flare.size,
  76072. position: flare.position,
  76073. color: flare.color.asArray(),
  76074. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  76075. });
  76076. }
  76077. return serializationObject;
  76078. };
  76079. return LensFlareSystem;
  76080. }());
  76081. BABYLON.LensFlareSystem = LensFlareSystem;
  76082. })(BABYLON || (BABYLON = {}));
  76083. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  76084. "use strict";
  76085. var BABYLON;
  76086. (function (BABYLON) {
  76087. /**
  76088. * This is a holder class for the physics joint created by the physics plugin.
  76089. * It holds a set of functions to control the underlying joint.
  76090. */
  76091. var PhysicsJoint = /** @class */ (function () {
  76092. function PhysicsJoint(type, jointData) {
  76093. this.type = type;
  76094. this.jointData = jointData;
  76095. jointData.nativeParams = jointData.nativeParams || {};
  76096. }
  76097. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  76098. get: function () {
  76099. return this._physicsJoint;
  76100. },
  76101. set: function (newJoint) {
  76102. if (this._physicsJoint) {
  76103. //remove from the wolrd
  76104. }
  76105. this._physicsJoint = newJoint;
  76106. },
  76107. enumerable: true,
  76108. configurable: true
  76109. });
  76110. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  76111. set: function (physicsPlugin) {
  76112. this._physicsPlugin = physicsPlugin;
  76113. },
  76114. enumerable: true,
  76115. configurable: true
  76116. });
  76117. /**
  76118. * Execute a function that is physics-plugin specific.
  76119. * @param {Function} func the function that will be executed.
  76120. * It accepts two parameters: the physics world and the physics joint.
  76121. */
  76122. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  76123. func(this._physicsPlugin.world, this._physicsJoint);
  76124. };
  76125. //TODO check if the native joints are the same
  76126. //Joint Types
  76127. PhysicsJoint.DistanceJoint = 0;
  76128. PhysicsJoint.HingeJoint = 1;
  76129. PhysicsJoint.BallAndSocketJoint = 2;
  76130. PhysicsJoint.WheelJoint = 3;
  76131. PhysicsJoint.SliderJoint = 4;
  76132. //OIMO
  76133. PhysicsJoint.PrismaticJoint = 5;
  76134. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  76135. PhysicsJoint.UniversalJoint = 6;
  76136. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  76137. //Cannon
  76138. //Similar to a Ball-Joint. Different in params
  76139. PhysicsJoint.PointToPointJoint = 8;
  76140. //Cannon only at the moment
  76141. PhysicsJoint.SpringJoint = 9;
  76142. PhysicsJoint.LockJoint = 10;
  76143. return PhysicsJoint;
  76144. }());
  76145. BABYLON.PhysicsJoint = PhysicsJoint;
  76146. /**
  76147. * A class representing a physics distance joint.
  76148. */
  76149. var DistanceJoint = /** @class */ (function (_super) {
  76150. __extends(DistanceJoint, _super);
  76151. function DistanceJoint(jointData) {
  76152. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76153. }
  76154. /**
  76155. * Update the predefined distance.
  76156. */
  76157. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76158. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76159. };
  76160. return DistanceJoint;
  76161. }(PhysicsJoint));
  76162. BABYLON.DistanceJoint = DistanceJoint;
  76163. var MotorEnabledJoint = /** @class */ (function (_super) {
  76164. __extends(MotorEnabledJoint, _super);
  76165. function MotorEnabledJoint(type, jointData) {
  76166. return _super.call(this, type, jointData) || this;
  76167. }
  76168. /**
  76169. * Set the motor values.
  76170. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76171. * @param {number} force the force to apply
  76172. * @param {number} maxForce max force for this motor.
  76173. */
  76174. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76175. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76176. };
  76177. /**
  76178. * Set the motor's limits.
  76179. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76180. */
  76181. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76182. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76183. };
  76184. return MotorEnabledJoint;
  76185. }(PhysicsJoint));
  76186. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76187. /**
  76188. * This class represents a single hinge physics joint
  76189. */
  76190. var HingeJoint = /** @class */ (function (_super) {
  76191. __extends(HingeJoint, _super);
  76192. function HingeJoint(jointData) {
  76193. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76194. }
  76195. /**
  76196. * Set the motor values.
  76197. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76198. * @param {number} force the force to apply
  76199. * @param {number} maxForce max force for this motor.
  76200. */
  76201. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76202. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76203. };
  76204. /**
  76205. * Set the motor's limits.
  76206. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76207. */
  76208. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76209. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76210. };
  76211. return HingeJoint;
  76212. }(MotorEnabledJoint));
  76213. BABYLON.HingeJoint = HingeJoint;
  76214. /**
  76215. * This class represents a dual hinge physics joint (same as wheel joint)
  76216. */
  76217. var Hinge2Joint = /** @class */ (function (_super) {
  76218. __extends(Hinge2Joint, _super);
  76219. function Hinge2Joint(jointData) {
  76220. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  76221. }
  76222. /**
  76223. * Set the motor values.
  76224. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76225. * @param {number} force the force to apply
  76226. * @param {number} maxForce max force for this motor.
  76227. * @param {motorIndex} the motor's index, 0 or 1.
  76228. */
  76229. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  76230. if (motorIndex === void 0) { motorIndex = 0; }
  76231. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  76232. };
  76233. /**
  76234. * Set the motor limits.
  76235. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76236. * @param {number} upperLimit the upper limit
  76237. * @param {number} lowerLimit lower limit
  76238. * @param {motorIndex} the motor's index, 0 or 1.
  76239. */
  76240. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  76241. if (motorIndex === void 0) { motorIndex = 0; }
  76242. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  76243. };
  76244. return Hinge2Joint;
  76245. }(MotorEnabledJoint));
  76246. BABYLON.Hinge2Joint = Hinge2Joint;
  76247. })(BABYLON || (BABYLON = {}));
  76248. //# sourceMappingURL=babylon.physicsJoint.js.map
  76249. "use strict";
  76250. var BABYLON;
  76251. (function (BABYLON) {
  76252. var PhysicsImpostor = /** @class */ (function () {
  76253. function PhysicsImpostor(object, type, _options, _scene) {
  76254. if (_options === void 0) { _options = { mass: 0 }; }
  76255. var _this = this;
  76256. this.object = object;
  76257. this.type = type;
  76258. this._options = _options;
  76259. this._scene = _scene;
  76260. this._bodyUpdateRequired = false;
  76261. this._onBeforePhysicsStepCallbacks = new Array();
  76262. this._onAfterPhysicsStepCallbacks = new Array();
  76263. this._onPhysicsCollideCallbacks = [];
  76264. this._deltaPosition = BABYLON.Vector3.Zero();
  76265. this._isDisposed = false;
  76266. //temp variables for parent rotation calculations
  76267. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  76268. this._tmpQuat = new BABYLON.Quaternion();
  76269. this._tmpQuat2 = new BABYLON.Quaternion();
  76270. /**
  76271. * this function is executed by the physics engine.
  76272. */
  76273. this.beforeStep = function () {
  76274. if (!_this._physicsEngine) {
  76275. return;
  76276. }
  76277. _this.object.translate(_this._deltaPosition, -1);
  76278. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  76279. _this.object.computeWorldMatrix(false);
  76280. if (_this.object.parent && _this.object.rotationQuaternion) {
  76281. _this.getParentsRotation();
  76282. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  76283. }
  76284. else {
  76285. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  76286. }
  76287. if (!_this._options.disableBidirectionalTransformation) {
  76288. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  76289. }
  76290. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  76291. func(_this);
  76292. });
  76293. };
  76294. /**
  76295. * this function is executed by the physics engine.
  76296. */
  76297. this.afterStep = function () {
  76298. if (!_this._physicsEngine) {
  76299. return;
  76300. }
  76301. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  76302. func(_this);
  76303. });
  76304. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  76305. // object has now its world rotation. needs to be converted to local.
  76306. if (_this.object.parent && _this.object.rotationQuaternion) {
  76307. _this.getParentsRotation();
  76308. _this._tmpQuat.conjugateInPlace();
  76309. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  76310. }
  76311. // take the position set and make it the absolute position of this object.
  76312. _this.object.setAbsolutePosition(_this.object.position);
  76313. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  76314. _this.object.translate(_this._deltaPosition, 1);
  76315. };
  76316. /**
  76317. * Legacy collision detection event support
  76318. */
  76319. this.onCollideEvent = null;
  76320. //event and body object due to cannon's event-based architecture.
  76321. this.onCollide = function (e) {
  76322. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  76323. return;
  76324. }
  76325. if (!_this._physicsEngine) {
  76326. return;
  76327. }
  76328. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  76329. if (otherImpostor) {
  76330. // Legacy collision detection event support
  76331. if (_this.onCollideEvent) {
  76332. _this.onCollideEvent(_this, otherImpostor);
  76333. }
  76334. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  76335. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  76336. }).forEach(function (obj) {
  76337. obj.callback(_this, otherImpostor);
  76338. });
  76339. }
  76340. };
  76341. //sanity check!
  76342. if (!this.object) {
  76343. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  76344. return;
  76345. }
  76346. //legacy support for old syntax.
  76347. if (!this._scene && object.getScene) {
  76348. this._scene = object.getScene();
  76349. }
  76350. if (!this._scene) {
  76351. return;
  76352. }
  76353. this._physicsEngine = this._scene.getPhysicsEngine();
  76354. if (!this._physicsEngine) {
  76355. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  76356. }
  76357. else {
  76358. //set the object's quaternion, if not set
  76359. if (!this.object.rotationQuaternion) {
  76360. if (this.object.rotation) {
  76361. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  76362. }
  76363. else {
  76364. this.object.rotationQuaternion = new BABYLON.Quaternion();
  76365. }
  76366. }
  76367. //default options params
  76368. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  76369. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  76370. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  76371. this._joints = [];
  76372. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  76373. if (!this.object.parent || this._options.ignoreParent) {
  76374. this._init();
  76375. }
  76376. else if (this.object.parent.physicsImpostor) {
  76377. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  76378. }
  76379. }
  76380. }
  76381. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  76382. get: function () {
  76383. return this._isDisposed;
  76384. },
  76385. enumerable: true,
  76386. configurable: true
  76387. });
  76388. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  76389. get: function () {
  76390. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  76391. },
  76392. set: function (value) {
  76393. this.setMass(value);
  76394. },
  76395. enumerable: true,
  76396. configurable: true
  76397. });
  76398. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  76399. get: function () {
  76400. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  76401. },
  76402. set: function (value) {
  76403. if (!this._physicsEngine) {
  76404. return;
  76405. }
  76406. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  76407. },
  76408. enumerable: true,
  76409. configurable: true
  76410. });
  76411. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  76412. get: function () {
  76413. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  76414. },
  76415. set: function (value) {
  76416. if (!this._physicsEngine) {
  76417. return;
  76418. }
  76419. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  76420. },
  76421. enumerable: true,
  76422. configurable: true
  76423. });
  76424. /**
  76425. * This function will completly initialize this impostor.
  76426. * It will create a new body - but only if this mesh has no parent.
  76427. * If it has, this impostor will not be used other than to define the impostor
  76428. * of the child mesh.
  76429. */
  76430. PhysicsImpostor.prototype._init = function () {
  76431. if (!this._physicsEngine) {
  76432. return;
  76433. }
  76434. this._physicsEngine.removeImpostor(this);
  76435. this.physicsBody = null;
  76436. this._parent = this._parent || this._getPhysicsParent();
  76437. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  76438. this._physicsEngine.addImpostor(this);
  76439. }
  76440. };
  76441. PhysicsImpostor.prototype._getPhysicsParent = function () {
  76442. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  76443. var parentMesh = this.object.parent;
  76444. return parentMesh.physicsImpostor;
  76445. }
  76446. return null;
  76447. };
  76448. /**
  76449. * Should a new body be generated.
  76450. */
  76451. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  76452. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  76453. };
  76454. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  76455. this.forceUpdate();
  76456. };
  76457. /**
  76458. * Force a regeneration of this or the parent's impostor's body.
  76459. * Use under cautious - This will remove all joints already implemented.
  76460. */
  76461. PhysicsImpostor.prototype.forceUpdate = function () {
  76462. this._init();
  76463. if (this.parent && !this._options.ignoreParent) {
  76464. this.parent.forceUpdate();
  76465. }
  76466. };
  76467. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  76468. /*public get mesh(): AbstractMesh {
  76469. return this._mesh;
  76470. }*/
  76471. /**
  76472. * Gets the body that holds this impostor. Either its own, or its parent.
  76473. */
  76474. get: function () {
  76475. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  76476. },
  76477. /**
  76478. * Set the physics body. Used mainly by the physics engine/plugin
  76479. */
  76480. set: function (physicsBody) {
  76481. if (this._physicsBody && this._physicsEngine) {
  76482. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  76483. }
  76484. this._physicsBody = physicsBody;
  76485. this.resetUpdateFlags();
  76486. },
  76487. enumerable: true,
  76488. configurable: true
  76489. });
  76490. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  76491. get: function () {
  76492. return !this._options.ignoreParent && this._parent ? this._parent : null;
  76493. },
  76494. set: function (value) {
  76495. this._parent = value;
  76496. },
  76497. enumerable: true,
  76498. configurable: true
  76499. });
  76500. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  76501. this._bodyUpdateRequired = false;
  76502. };
  76503. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  76504. if (this.object.getBoundingInfo) {
  76505. var q = this.object.rotationQuaternion;
  76506. //reset rotation
  76507. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  76508. //calculate the world matrix with no rotation
  76509. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76510. var boundingInfo = this.object.getBoundingInfo();
  76511. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  76512. //bring back the rotation
  76513. this.object.rotationQuaternion = q;
  76514. //calculate the world matrix with the new rotation
  76515. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  76516. return size;
  76517. }
  76518. else {
  76519. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  76520. }
  76521. };
  76522. PhysicsImpostor.prototype.getObjectCenter = function () {
  76523. if (this.object.getBoundingInfo) {
  76524. var boundingInfo = this.object.getBoundingInfo();
  76525. return boundingInfo.boundingBox.centerWorld;
  76526. }
  76527. else {
  76528. return this.object.position;
  76529. }
  76530. };
  76531. /**
  76532. * Get a specific parametes from the options parameter.
  76533. */
  76534. PhysicsImpostor.prototype.getParam = function (paramName) {
  76535. return this._options[paramName];
  76536. };
  76537. /**
  76538. * Sets a specific parameter in the options given to the physics plugin
  76539. */
  76540. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  76541. this._options[paramName] = value;
  76542. this._bodyUpdateRequired = true;
  76543. };
  76544. /**
  76545. * Specifically change the body's mass option. Won't recreate the physics body object
  76546. */
  76547. PhysicsImpostor.prototype.setMass = function (mass) {
  76548. if (this.getParam("mass") !== mass) {
  76549. this.setParam("mass", mass);
  76550. }
  76551. if (this._physicsEngine) {
  76552. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  76553. }
  76554. };
  76555. PhysicsImpostor.prototype.getLinearVelocity = function () {
  76556. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  76557. };
  76558. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  76559. if (this._physicsEngine) {
  76560. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  76561. }
  76562. };
  76563. PhysicsImpostor.prototype.getAngularVelocity = function () {
  76564. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  76565. };
  76566. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  76567. if (this._physicsEngine) {
  76568. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  76569. }
  76570. };
  76571. /**
  76572. * Execute a function with the physics plugin native code.
  76573. * Provide a function the will have two variables - the world object and the physics body object.
  76574. */
  76575. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  76576. if (this._physicsEngine) {
  76577. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  76578. }
  76579. };
  76580. /**
  76581. * Register a function that will be executed before the physics world is stepping forward.
  76582. */
  76583. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  76584. this._onBeforePhysicsStepCallbacks.push(func);
  76585. };
  76586. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  76587. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  76588. if (index > -1) {
  76589. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  76590. }
  76591. else {
  76592. BABYLON.Tools.Warn("Function to remove was not found");
  76593. }
  76594. };
  76595. /**
  76596. * Register a function that will be executed after the physics step
  76597. */
  76598. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  76599. this._onAfterPhysicsStepCallbacks.push(func);
  76600. };
  76601. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  76602. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  76603. if (index > -1) {
  76604. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  76605. }
  76606. else {
  76607. BABYLON.Tools.Warn("Function to remove was not found");
  76608. }
  76609. };
  76610. /**
  76611. * register a function that will be executed when this impostor collides against a different body.
  76612. */
  76613. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  76614. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76615. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  76616. };
  76617. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  76618. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  76619. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  76620. if (index > -1) {
  76621. this._onPhysicsCollideCallbacks.splice(index, 1);
  76622. }
  76623. else {
  76624. BABYLON.Tools.Warn("Function to remove was not found");
  76625. }
  76626. };
  76627. PhysicsImpostor.prototype.getParentsRotation = function () {
  76628. var parent = this.object.parent;
  76629. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  76630. while (parent) {
  76631. if (parent.rotationQuaternion) {
  76632. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  76633. }
  76634. else {
  76635. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  76636. }
  76637. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  76638. parent = parent.parent;
  76639. }
  76640. return this._tmpQuat;
  76641. };
  76642. /**
  76643. * Apply a force
  76644. */
  76645. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  76646. if (this._physicsEngine) {
  76647. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  76648. }
  76649. return this;
  76650. };
  76651. /**
  76652. * Apply an impulse
  76653. */
  76654. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  76655. if (this._physicsEngine) {
  76656. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  76657. }
  76658. return this;
  76659. };
  76660. /**
  76661. * A help function to create a joint.
  76662. */
  76663. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  76664. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  76665. this.addJoint(otherImpostor, joint);
  76666. return this;
  76667. };
  76668. /**
  76669. * Add a joint to this impostor with a different impostor.
  76670. */
  76671. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  76672. this._joints.push({
  76673. otherImpostor: otherImpostor,
  76674. joint: joint
  76675. });
  76676. if (this._physicsEngine) {
  76677. this._physicsEngine.addJoint(this, otherImpostor, joint);
  76678. }
  76679. return this;
  76680. };
  76681. /**
  76682. * Will keep this body still, in a sleep mode.
  76683. */
  76684. PhysicsImpostor.prototype.sleep = function () {
  76685. if (this._physicsEngine) {
  76686. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  76687. }
  76688. return this;
  76689. };
  76690. /**
  76691. * Wake the body up.
  76692. */
  76693. PhysicsImpostor.prototype.wakeUp = function () {
  76694. if (this._physicsEngine) {
  76695. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  76696. }
  76697. return this;
  76698. };
  76699. PhysicsImpostor.prototype.clone = function (newObject) {
  76700. if (!newObject)
  76701. return null;
  76702. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  76703. };
  76704. PhysicsImpostor.prototype.dispose = function () {
  76705. var _this = this;
  76706. //no dispose if no physics engine is available.
  76707. if (!this._physicsEngine) {
  76708. return;
  76709. }
  76710. this._joints.forEach(function (j) {
  76711. if (_this._physicsEngine) {
  76712. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  76713. }
  76714. });
  76715. //dispose the physics body
  76716. this._physicsEngine.removeImpostor(this);
  76717. if (this.parent) {
  76718. this.parent.forceUpdate();
  76719. }
  76720. else {
  76721. /*this._object.getChildMeshes().forEach(function(mesh) {
  76722. if (mesh.physicsImpostor) {
  76723. if (disposeChildren) {
  76724. mesh.physicsImpostor.dispose();
  76725. mesh.physicsImpostor = null;
  76726. }
  76727. }
  76728. })*/
  76729. }
  76730. this._isDisposed = true;
  76731. };
  76732. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  76733. this._deltaPosition.copyFrom(position);
  76734. };
  76735. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  76736. if (!this._deltaRotation) {
  76737. this._deltaRotation = new BABYLON.Quaternion();
  76738. }
  76739. this._deltaRotation.copyFrom(rotation);
  76740. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  76741. };
  76742. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  76743. if (this._physicsEngine) {
  76744. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  76745. }
  76746. return this;
  76747. };
  76748. PhysicsImpostor.prototype.getRadius = function () {
  76749. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  76750. };
  76751. /**
  76752. * Sync a bone with this impostor
  76753. * @param bone The bone to sync to the impostor.
  76754. * @param boneMesh The mesh that the bone is influencing.
  76755. * @param jointPivot The pivot of the joint / bone in local space.
  76756. * @param distToJoint Optional distance from the impostor to the joint.
  76757. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76758. */
  76759. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  76760. var tempVec = PhysicsImpostor._tmpVecs[0];
  76761. var mesh = this.object;
  76762. if (mesh.rotationQuaternion) {
  76763. if (adjustRotation) {
  76764. var tempQuat = PhysicsImpostor._tmpQuat;
  76765. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  76766. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  76767. }
  76768. else {
  76769. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  76770. }
  76771. }
  76772. tempVec.x = 0;
  76773. tempVec.y = 0;
  76774. tempVec.z = 0;
  76775. if (jointPivot) {
  76776. tempVec.x = jointPivot.x;
  76777. tempVec.y = jointPivot.y;
  76778. tempVec.z = jointPivot.z;
  76779. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  76780. if (distToJoint === undefined || distToJoint === null) {
  76781. distToJoint = jointPivot.length();
  76782. }
  76783. tempVec.x *= distToJoint;
  76784. tempVec.y *= distToJoint;
  76785. tempVec.z *= distToJoint;
  76786. }
  76787. if (bone.getParent()) {
  76788. tempVec.addInPlace(mesh.getAbsolutePosition());
  76789. bone.setAbsolutePosition(tempVec, boneMesh);
  76790. }
  76791. else {
  76792. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  76793. boneMesh.position.x -= tempVec.x;
  76794. boneMesh.position.y -= tempVec.y;
  76795. boneMesh.position.z -= tempVec.z;
  76796. }
  76797. };
  76798. /**
  76799. * Sync impostor to a bone
  76800. * @param bone The bone that the impostor will be synced to.
  76801. * @param boneMesh The mesh that the bone is influencing.
  76802. * @param jointPivot The pivot of the joint / bone in local space.
  76803. * @param distToJoint Optional distance from the impostor to the joint.
  76804. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  76805. * @param boneAxis Optional vector3 axis the bone is aligned with
  76806. */
  76807. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  76808. var mesh = this.object;
  76809. if (mesh.rotationQuaternion) {
  76810. if (adjustRotation) {
  76811. var tempQuat = PhysicsImpostor._tmpQuat;
  76812. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  76813. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  76814. }
  76815. else {
  76816. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  76817. }
  76818. }
  76819. var pos = PhysicsImpostor._tmpVecs[0];
  76820. var boneDir = PhysicsImpostor._tmpVecs[1];
  76821. if (!boneAxis) {
  76822. boneAxis = PhysicsImpostor._tmpVecs[2];
  76823. boneAxis.x = 0;
  76824. boneAxis.y = 1;
  76825. boneAxis.z = 0;
  76826. }
  76827. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  76828. bone.getAbsolutePositionToRef(boneMesh, pos);
  76829. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  76830. distToJoint = jointPivot.length();
  76831. }
  76832. if (distToJoint !== undefined && distToJoint !== null) {
  76833. pos.x += boneDir.x * distToJoint;
  76834. pos.y += boneDir.y * distToJoint;
  76835. pos.z += boneDir.z * distToJoint;
  76836. }
  76837. mesh.setAbsolutePosition(pos);
  76838. };
  76839. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  76840. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  76841. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76842. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  76843. //Impostor types
  76844. PhysicsImpostor.NoImpostor = 0;
  76845. PhysicsImpostor.SphereImpostor = 1;
  76846. PhysicsImpostor.BoxImpostor = 2;
  76847. PhysicsImpostor.PlaneImpostor = 3;
  76848. PhysicsImpostor.MeshImpostor = 4;
  76849. PhysicsImpostor.CylinderImpostor = 7;
  76850. PhysicsImpostor.ParticleImpostor = 8;
  76851. PhysicsImpostor.HeightmapImpostor = 9;
  76852. return PhysicsImpostor;
  76853. }());
  76854. BABYLON.PhysicsImpostor = PhysicsImpostor;
  76855. })(BABYLON || (BABYLON = {}));
  76856. //# sourceMappingURL=babylon.physicsImpostor.js.map
  76857. "use strict";
  76858. var BABYLON;
  76859. (function (BABYLON) {
  76860. var PhysicsEngine = /** @class */ (function () {
  76861. function PhysicsEngine(gravity, _physicsPlugin) {
  76862. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  76863. this._physicsPlugin = _physicsPlugin;
  76864. //new methods and parameters
  76865. this._impostors = [];
  76866. this._joints = [];
  76867. if (!this._physicsPlugin.isSupported()) {
  76868. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  76869. + "Please make sure it is included.");
  76870. }
  76871. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  76872. this.setGravity(gravity);
  76873. this.setTimeStep();
  76874. }
  76875. PhysicsEngine.prototype.setGravity = function (gravity) {
  76876. this.gravity = gravity;
  76877. this._physicsPlugin.setGravity(this.gravity);
  76878. };
  76879. /**
  76880. * Set the time step of the physics engine.
  76881. * default is 1/60.
  76882. * To slow it down, enter 1/600 for example.
  76883. * To speed it up, 1/30
  76884. * @param {number} newTimeStep the new timestep to apply to this world.
  76885. */
  76886. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  76887. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  76888. this._physicsPlugin.setTimeStep(newTimeStep);
  76889. };
  76890. /**
  76891. * Get the time step of the physics engine.
  76892. */
  76893. PhysicsEngine.prototype.getTimeStep = function () {
  76894. return this._physicsPlugin.getTimeStep();
  76895. };
  76896. PhysicsEngine.prototype.dispose = function () {
  76897. this._impostors.forEach(function (impostor) {
  76898. impostor.dispose();
  76899. });
  76900. this._physicsPlugin.dispose();
  76901. };
  76902. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  76903. return this._physicsPlugin.name;
  76904. };
  76905. /**
  76906. * Adding a new impostor for the impostor tracking.
  76907. * This will be done by the impostor itself.
  76908. * @param {PhysicsImpostor} impostor the impostor to add
  76909. */
  76910. PhysicsEngine.prototype.addImpostor = function (impostor) {
  76911. impostor.uniqueId = this._impostors.push(impostor);
  76912. //if no parent, generate the body
  76913. if (!impostor.parent) {
  76914. this._physicsPlugin.generatePhysicsBody(impostor);
  76915. }
  76916. };
  76917. /**
  76918. * Remove an impostor from the engine.
  76919. * This impostor and its mesh will not longer be updated by the physics engine.
  76920. * @param {PhysicsImpostor} impostor the impostor to remove
  76921. */
  76922. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  76923. var index = this._impostors.indexOf(impostor);
  76924. if (index > -1) {
  76925. var removed = this._impostors.splice(index, 1);
  76926. //Is it needed?
  76927. if (removed.length) {
  76928. //this will also remove it from the world.
  76929. removed[0].physicsBody = null;
  76930. }
  76931. }
  76932. };
  76933. /**
  76934. * Add a joint to the physics engine
  76935. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  76936. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  76937. * @param {PhysicsJoint} the joint that will connect both impostors.
  76938. */
  76939. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  76940. var impostorJoint = {
  76941. mainImpostor: mainImpostor,
  76942. connectedImpostor: connectedImpostor,
  76943. joint: joint
  76944. };
  76945. joint.physicsPlugin = this._physicsPlugin;
  76946. this._joints.push(impostorJoint);
  76947. this._physicsPlugin.generateJoint(impostorJoint);
  76948. };
  76949. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  76950. var matchingJoints = this._joints.filter(function (impostorJoint) {
  76951. return (impostorJoint.connectedImpostor === connectedImpostor
  76952. && impostorJoint.joint === joint
  76953. && impostorJoint.mainImpostor === mainImpostor);
  76954. });
  76955. if (matchingJoints.length) {
  76956. this._physicsPlugin.removeJoint(matchingJoints[0]);
  76957. //TODO remove it from the list as well
  76958. }
  76959. };
  76960. /**
  76961. * Called by the scene. no need to call it.
  76962. */
  76963. PhysicsEngine.prototype._step = function (delta) {
  76964. var _this = this;
  76965. //check if any mesh has no body / requires an update
  76966. this._impostors.forEach(function (impostor) {
  76967. if (impostor.isBodyInitRequired()) {
  76968. _this._physicsPlugin.generatePhysicsBody(impostor);
  76969. }
  76970. });
  76971. if (delta > 0.1) {
  76972. delta = 0.1;
  76973. }
  76974. else if (delta <= 0) {
  76975. delta = 1.0 / 60.0;
  76976. }
  76977. this._physicsPlugin.executeStep(delta, this._impostors);
  76978. };
  76979. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  76980. return this._physicsPlugin;
  76981. };
  76982. PhysicsEngine.prototype.getImpostors = function () {
  76983. return this._impostors;
  76984. };
  76985. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  76986. for (var i = 0; i < this._impostors.length; ++i) {
  76987. if (this._impostors[i].object === object) {
  76988. return this._impostors[i];
  76989. }
  76990. }
  76991. return null;
  76992. };
  76993. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  76994. for (var i = 0; i < this._impostors.length; ++i) {
  76995. if (this._impostors[i].physicsBody === body) {
  76996. return this._impostors[i];
  76997. }
  76998. }
  76999. return null;
  77000. };
  77001. // Statics
  77002. PhysicsEngine.Epsilon = 0.001;
  77003. return PhysicsEngine;
  77004. }());
  77005. BABYLON.PhysicsEngine = PhysicsEngine;
  77006. })(BABYLON || (BABYLON = {}));
  77007. //# sourceMappingURL=babylon.physicsEngine.js.map
  77008. "use strict";
  77009. var BABYLON;
  77010. (function (BABYLON) {
  77011. var PhysicsHelper = /** @class */ (function () {
  77012. function PhysicsHelper(scene) {
  77013. this._scene = scene;
  77014. this._physicsEngine = this._scene.getPhysicsEngine();
  77015. if (!this._physicsEngine) {
  77016. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  77017. }
  77018. }
  77019. /**
  77020. * @param {Vector3} origin the origin of the explosion
  77021. * @param {number} radius the explosion radius
  77022. * @param {number} strength the explosion strength
  77023. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77024. */
  77025. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  77026. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77027. if (!this._physicsEngine) {
  77028. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  77029. return null;
  77030. }
  77031. var impostors = this._physicsEngine.getImpostors();
  77032. if (impostors.length === 0) {
  77033. return null;
  77034. }
  77035. var event = new PhysicsRadialExplosionEvent(this._scene);
  77036. impostors.forEach(function (impostor) {
  77037. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77038. if (!impostorForceAndContactPoint) {
  77039. return;
  77040. }
  77041. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77042. });
  77043. event.dispose(false);
  77044. return event;
  77045. };
  77046. /**
  77047. * @param {Vector3} origin the origin of the explosion
  77048. * @param {number} radius the explosion radius
  77049. * @param {number} strength the explosion strength
  77050. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77051. */
  77052. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  77053. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77054. if (!this._physicsEngine) {
  77055. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77056. return null;
  77057. }
  77058. var impostors = this._physicsEngine.getImpostors();
  77059. if (impostors.length === 0) {
  77060. return null;
  77061. }
  77062. var event = new PhysicsRadialExplosionEvent(this._scene);
  77063. impostors.forEach(function (impostor) {
  77064. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77065. if (!impostorForceAndContactPoint) {
  77066. return;
  77067. }
  77068. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77069. });
  77070. event.dispose(false);
  77071. return event;
  77072. };
  77073. /**
  77074. * @param {Vector3} origin the origin of the explosion
  77075. * @param {number} radius the explosion radius
  77076. * @param {number} strength the explosion strength
  77077. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77078. */
  77079. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  77080. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77081. if (!this._physicsEngine) {
  77082. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77083. return null;
  77084. }
  77085. var impostors = this._physicsEngine.getImpostors();
  77086. if (impostors.length === 0) {
  77087. return null;
  77088. }
  77089. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  77090. event.dispose(false);
  77091. return event;
  77092. };
  77093. /**
  77094. * @param {Vector3} origin the origin of the updraft
  77095. * @param {number} radius the radius of the updraft
  77096. * @param {number} strength the strength of the updraft
  77097. * @param {number} height the height of the updraft
  77098. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  77099. */
  77100. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  77101. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  77102. if (!this._physicsEngine) {
  77103. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77104. return null;
  77105. }
  77106. if (this._physicsEngine.getImpostors().length === 0) {
  77107. return null;
  77108. }
  77109. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  77110. event.dispose(false);
  77111. return event;
  77112. };
  77113. /**
  77114. * @param {Vector3} origin the of the vortex
  77115. * @param {number} radius the radius of the vortex
  77116. * @param {number} strength the strength of the vortex
  77117. * @param {number} height the height of the vortex
  77118. */
  77119. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  77120. if (!this._physicsEngine) {
  77121. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77122. return null;
  77123. }
  77124. if (this._physicsEngine.getImpostors().length === 0) {
  77125. return null;
  77126. }
  77127. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  77128. event.dispose(false);
  77129. return event;
  77130. };
  77131. return PhysicsHelper;
  77132. }());
  77133. BABYLON.PhysicsHelper = PhysicsHelper;
  77134. /***** Radial explosion *****/
  77135. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  77136. function PhysicsRadialExplosionEvent(scene) {
  77137. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  77138. this._rays = [];
  77139. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  77140. this._scene = scene;
  77141. }
  77142. /**
  77143. * Returns the data related to the radial explosion event (sphere & rays).
  77144. * @returns {PhysicsRadialExplosionEventData}
  77145. */
  77146. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77147. this._dataFetched = true;
  77148. return {
  77149. sphere: this._sphere,
  77150. rays: this._rays,
  77151. };
  77152. };
  77153. /**
  77154. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77155. * @param impostor
  77156. * @param {Vector3} origin the origin of the explosion
  77157. * @param {number} radius the explosion radius
  77158. * @param {number} strength the explosion strength
  77159. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77160. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77161. */
  77162. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77163. if (impostor.mass === 0) {
  77164. return null;
  77165. }
  77166. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77167. return null;
  77168. }
  77169. if (impostor.object.getClassName() !== 'Mesh') {
  77170. return null;
  77171. }
  77172. var impostorObject = impostor.object;
  77173. var impostorObjectCenter = impostor.getObjectCenter();
  77174. var direction = impostorObjectCenter.subtract(origin);
  77175. var ray = new BABYLON.Ray(origin, direction, radius);
  77176. this._rays.push(ray);
  77177. var hit = ray.intersectsMesh(impostorObject);
  77178. var contactPoint = hit.pickedPoint;
  77179. if (!contactPoint) {
  77180. return null;
  77181. }
  77182. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77183. if (distanceFromOrigin > radius) {
  77184. return null;
  77185. }
  77186. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77187. ? strength
  77188. : strength * (1 - (distanceFromOrigin / radius));
  77189. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77190. return { force: force, contactPoint: contactPoint };
  77191. };
  77192. /**
  77193. * Disposes the sphere.
  77194. * @param {bolean} force
  77195. */
  77196. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77197. var _this = this;
  77198. if (force === void 0) { force = true; }
  77199. if (force) {
  77200. this._sphere.dispose();
  77201. }
  77202. else {
  77203. setTimeout(function () {
  77204. if (!_this._dataFetched) {
  77205. _this._sphere.dispose();
  77206. }
  77207. }, 0);
  77208. }
  77209. };
  77210. /*** Helpers ***/
  77211. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77212. if (!this._sphere) {
  77213. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77214. this._sphere.isVisible = false;
  77215. }
  77216. };
  77217. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77218. var impostorObject = impostor.object;
  77219. this._prepareSphere();
  77220. this._sphere.position = origin;
  77221. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  77222. this._sphere._updateBoundingInfo();
  77223. this._sphere.computeWorldMatrix(true);
  77224. return this._sphere.intersectsMesh(impostorObject, true);
  77225. };
  77226. return PhysicsRadialExplosionEvent;
  77227. }());
  77228. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  77229. /***** Gravitational Field *****/
  77230. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  77231. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  77232. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77233. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77234. this._physicsHelper = physicsHelper;
  77235. this._scene = scene;
  77236. this._origin = origin;
  77237. this._radius = radius;
  77238. this._strength = strength;
  77239. this._falloff = falloff;
  77240. this._tickCallback = this._tick.bind(this);
  77241. }
  77242. /**
  77243. * Returns the data related to the gravitational field event (sphere).
  77244. * @returns {PhysicsGravitationalFieldEventData}
  77245. */
  77246. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  77247. this._dataFetched = true;
  77248. return {
  77249. sphere: this._sphere,
  77250. };
  77251. };
  77252. /**
  77253. * Enables the gravitational field.
  77254. */
  77255. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  77256. this._tickCallback.call(this);
  77257. this._scene.registerBeforeRender(this._tickCallback);
  77258. };
  77259. /**
  77260. * Disables the gravitational field.
  77261. */
  77262. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  77263. this._scene.unregisterBeforeRender(this._tickCallback);
  77264. };
  77265. /**
  77266. * Disposes the sphere.
  77267. * @param {bolean} force
  77268. */
  77269. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  77270. var _this = this;
  77271. if (force === void 0) { force = true; }
  77272. if (force) {
  77273. this._sphere.dispose();
  77274. }
  77275. else {
  77276. setTimeout(function () {
  77277. if (!_this._dataFetched) {
  77278. _this._sphere.dispose();
  77279. }
  77280. }, 0);
  77281. }
  77282. };
  77283. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  77284. // Since the params won't change, we fetch the event only once
  77285. if (this._sphere) {
  77286. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77287. }
  77288. else {
  77289. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77290. if (radialExplosionEvent) {
  77291. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  77292. }
  77293. }
  77294. };
  77295. return PhysicsGravitationalFieldEvent;
  77296. }());
  77297. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  77298. /***** Updraft *****/
  77299. var PhysicsUpdraftEvent = /** @class */ (function () {
  77300. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  77301. this._scene = _scene;
  77302. this._origin = _origin;
  77303. this._radius = _radius;
  77304. this._strength = _strength;
  77305. this._height = _height;
  77306. this._updraftMode = _updraftMode;
  77307. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77308. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  77309. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77310. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77311. this._physicsEngine = this._scene.getPhysicsEngine();
  77312. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77313. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77314. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77315. this._originDirection = this._origin.subtract(this._originTop).normalize();
  77316. }
  77317. this._tickCallback = this._tick.bind(this);
  77318. }
  77319. /**
  77320. * Returns the data related to the updraft event (cylinder).
  77321. * @returns {PhysicsUpdraftEventData}
  77322. */
  77323. PhysicsUpdraftEvent.prototype.getData = function () {
  77324. this._dataFetched = true;
  77325. return {
  77326. cylinder: this._cylinder,
  77327. };
  77328. };
  77329. /**
  77330. * Enables the updraft.
  77331. */
  77332. PhysicsUpdraftEvent.prototype.enable = function () {
  77333. this._tickCallback.call(this);
  77334. this._scene.registerBeforeRender(this._tickCallback);
  77335. };
  77336. /**
  77337. * Disables the cortex.
  77338. */
  77339. PhysicsUpdraftEvent.prototype.disable = function () {
  77340. this._scene.unregisterBeforeRender(this._tickCallback);
  77341. };
  77342. /**
  77343. * Disposes the sphere.
  77344. * @param {bolean} force
  77345. */
  77346. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  77347. var _this = this;
  77348. if (force === void 0) { force = true; }
  77349. if (force) {
  77350. this._cylinder.dispose();
  77351. }
  77352. else {
  77353. setTimeout(function () {
  77354. if (!_this._dataFetched) {
  77355. _this._cylinder.dispose();
  77356. }
  77357. }, 0);
  77358. }
  77359. };
  77360. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77361. if (impostor.mass === 0) {
  77362. return null;
  77363. }
  77364. if (!this._intersectsWithCylinder(impostor)) {
  77365. return null;
  77366. }
  77367. var impostorObjectCenter = impostor.getObjectCenter();
  77368. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  77369. var direction = this._originDirection;
  77370. }
  77371. else {
  77372. var direction = impostorObjectCenter.subtract(this._originTop);
  77373. }
  77374. var multiplier = this._strength * -1;
  77375. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77376. return { force: force, contactPoint: impostorObjectCenter };
  77377. };
  77378. PhysicsUpdraftEvent.prototype._tick = function () {
  77379. var _this = this;
  77380. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77381. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77382. if (!impostorForceAndContactPoint) {
  77383. return;
  77384. }
  77385. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77386. });
  77387. };
  77388. /*** Helpers ***/
  77389. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  77390. if (!this._cylinder) {
  77391. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  77392. height: this._height,
  77393. diameter: this._radius * 2,
  77394. }, this._scene);
  77395. this._cylinder.isVisible = false;
  77396. }
  77397. };
  77398. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  77399. var impostorObject = impostor.object;
  77400. this._prepareCylinder();
  77401. this._cylinder.position = this._cylinderPosition;
  77402. return this._cylinder.intersectsMesh(impostorObject, true);
  77403. };
  77404. return PhysicsUpdraftEvent;
  77405. }());
  77406. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  77407. /***** Vortex *****/
  77408. var PhysicsVortexEvent = /** @class */ (function () {
  77409. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  77410. this._scene = _scene;
  77411. this._origin = _origin;
  77412. this._radius = _radius;
  77413. this._strength = _strength;
  77414. this._height = _height;
  77415. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  77416. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  77417. this._updraftMultiplier = 0.02;
  77418. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  77419. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77420. this._physicsEngine = this._scene.getPhysicsEngine();
  77421. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  77422. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  77423. this._tickCallback = this._tick.bind(this);
  77424. }
  77425. /**
  77426. * Returns the data related to the vortex event (cylinder).
  77427. * @returns {PhysicsVortexEventData}
  77428. */
  77429. PhysicsVortexEvent.prototype.getData = function () {
  77430. this._dataFetched = true;
  77431. return {
  77432. cylinder: this._cylinder,
  77433. };
  77434. };
  77435. /**
  77436. * Enables the vortex.
  77437. */
  77438. PhysicsVortexEvent.prototype.enable = function () {
  77439. this._tickCallback.call(this);
  77440. this._scene.registerBeforeRender(this._tickCallback);
  77441. };
  77442. /**
  77443. * Disables the cortex.
  77444. */
  77445. PhysicsVortexEvent.prototype.disable = function () {
  77446. this._scene.unregisterBeforeRender(this._tickCallback);
  77447. };
  77448. /**
  77449. * Disposes the sphere.
  77450. * @param {bolean} force
  77451. */
  77452. PhysicsVortexEvent.prototype.dispose = function (force) {
  77453. var _this = this;
  77454. if (force === void 0) { force = true; }
  77455. if (force) {
  77456. this._cylinder.dispose();
  77457. }
  77458. else {
  77459. setTimeout(function () {
  77460. if (!_this._dataFetched) {
  77461. _this._cylinder.dispose();
  77462. }
  77463. }, 0);
  77464. }
  77465. };
  77466. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  77467. if (impostor.mass === 0) {
  77468. return null;
  77469. }
  77470. if (!this._intersectsWithCylinder(impostor)) {
  77471. return null;
  77472. }
  77473. if (impostor.object.getClassName() !== 'Mesh') {
  77474. return null;
  77475. }
  77476. var impostorObject = impostor.object;
  77477. var impostorObjectCenter = impostor.getObjectCenter();
  77478. 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)
  77479. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  77480. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  77481. var hit = ray.intersectsMesh(impostorObject);
  77482. var contactPoint = hit.pickedPoint;
  77483. if (!contactPoint) {
  77484. return null;
  77485. }
  77486. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  77487. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  77488. var directionToOrigin = contactPoint.normalize();
  77489. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77490. directionToOrigin = directionToOrigin.negate();
  77491. }
  77492. // TODO: find a more physically based solution
  77493. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  77494. var forceX = directionToOrigin.x * this._strength / 8;
  77495. var forceY = directionToOrigin.y * this._updraftMultiplier;
  77496. var forceZ = directionToOrigin.z * this._strength / 8;
  77497. }
  77498. else {
  77499. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  77500. var forceY = this._originTop.y * this._updraftMultiplier;
  77501. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  77502. }
  77503. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  77504. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  77505. return { force: force, contactPoint: impostorObjectCenter };
  77506. };
  77507. PhysicsVortexEvent.prototype._tick = function () {
  77508. var _this = this;
  77509. this._physicsEngine.getImpostors().forEach(function (impostor) {
  77510. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  77511. if (!impostorForceAndContactPoint) {
  77512. return;
  77513. }
  77514. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77515. });
  77516. };
  77517. /*** Helpers ***/
  77518. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  77519. if (!this._cylinder) {
  77520. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  77521. height: this._height,
  77522. diameter: this._radius * 2,
  77523. }, this._scene);
  77524. this._cylinder.isVisible = false;
  77525. }
  77526. };
  77527. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  77528. var impostorObject = impostor.object;
  77529. this._prepareCylinder();
  77530. this._cylinder.position = this._cylinderPosition;
  77531. return this._cylinder.intersectsMesh(impostorObject, true);
  77532. };
  77533. return PhysicsVortexEvent;
  77534. }());
  77535. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  77536. /***** Enums *****/
  77537. /**
  77538. * The strenght of the force in correspondence to the distance of the affected object
  77539. */
  77540. var PhysicsRadialImpulseFalloff;
  77541. (function (PhysicsRadialImpulseFalloff) {
  77542. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  77543. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  77544. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  77545. /**
  77546. * The strenght of the force in correspondence to the distance of the affected object
  77547. */
  77548. var PhysicsUpdraftMode;
  77549. (function (PhysicsUpdraftMode) {
  77550. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  77551. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  77552. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  77553. })(BABYLON || (BABYLON = {}));
  77554. //# sourceMappingURL=babylon.physicsHelper.js.map
  77555. "use strict";
  77556. var BABYLON;
  77557. (function (BABYLON) {
  77558. var CannonJSPlugin = /** @class */ (function () {
  77559. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  77560. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  77561. if (iterations === void 0) { iterations = 10; }
  77562. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  77563. this.name = "CannonJSPlugin";
  77564. this._physicsMaterials = new Array();
  77565. this._fixedTimeStep = 1 / 60;
  77566. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  77567. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  77568. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  77569. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  77570. this._tmpPosition = BABYLON.Vector3.Zero();
  77571. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  77572. this._tmpUnityRotation = new BABYLON.Quaternion();
  77573. if (!this.isSupported()) {
  77574. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  77575. return;
  77576. }
  77577. this._extendNamespace();
  77578. this.world = new this.BJSCANNON.World();
  77579. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  77580. this.world.solver.iterations = iterations;
  77581. }
  77582. CannonJSPlugin.prototype.setGravity = function (gravity) {
  77583. this.world.gravity.copy(gravity);
  77584. };
  77585. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  77586. this._fixedTimeStep = timeStep;
  77587. };
  77588. CannonJSPlugin.prototype.getTimeStep = function () {
  77589. return this._fixedTimeStep;
  77590. };
  77591. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  77592. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  77593. };
  77594. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  77595. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77596. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77597. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  77598. };
  77599. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  77600. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  77601. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  77602. impostor.physicsBody.applyForce(impulse, worldPoint);
  77603. };
  77604. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  77605. //parent-child relationship. Does this impostor has a parent impostor?
  77606. if (impostor.parent) {
  77607. if (impostor.physicsBody) {
  77608. this.removePhysicsBody(impostor);
  77609. //TODO is that needed?
  77610. impostor.forceUpdate();
  77611. }
  77612. return;
  77613. }
  77614. //should a new body be created for this impostor?
  77615. if (impostor.isBodyInitRequired()) {
  77616. var shape = this._createShape(impostor);
  77617. //unregister events, if body is being changed
  77618. var oldBody = impostor.physicsBody;
  77619. if (oldBody) {
  77620. this.removePhysicsBody(impostor);
  77621. }
  77622. //create the body and material
  77623. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  77624. var bodyCreationObject = {
  77625. mass: impostor.getParam("mass"),
  77626. material: material
  77627. };
  77628. // A simple extend, in case native options were used.
  77629. var nativeOptions = impostor.getParam("nativeOptions");
  77630. for (var key in nativeOptions) {
  77631. if (nativeOptions.hasOwnProperty(key)) {
  77632. bodyCreationObject[key] = nativeOptions[key];
  77633. }
  77634. }
  77635. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  77636. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  77637. this.world.addEventListener("preStep", impostor.beforeStep);
  77638. this.world.addEventListener("postStep", impostor.afterStep);
  77639. impostor.physicsBody.addShape(shape);
  77640. this.world.add(impostor.physicsBody);
  77641. //try to keep the body moving in the right direction by taking old properties.
  77642. //Should be tested!
  77643. if (oldBody) {
  77644. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  77645. impostor.physicsBody[param].copy(oldBody[param]);
  77646. });
  77647. }
  77648. this._processChildMeshes(impostor);
  77649. }
  77650. //now update the body's transformation
  77651. this._updatePhysicsBodyTransformation(impostor);
  77652. };
  77653. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  77654. var _this = this;
  77655. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  77656. var currentRotation = mainImpostor.object.rotationQuaternion;
  77657. if (meshChildren.length) {
  77658. var processMesh = function (localPosition, mesh) {
  77659. if (!currentRotation || !mesh.rotationQuaternion) {
  77660. return;
  77661. }
  77662. var childImpostor = mesh.getPhysicsImpostor();
  77663. if (childImpostor) {
  77664. var parent = childImpostor.parent;
  77665. if (parent !== mainImpostor) {
  77666. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  77667. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  77668. if (childImpostor.physicsBody) {
  77669. _this.removePhysicsBody(childImpostor);
  77670. childImpostor.physicsBody = null;
  77671. }
  77672. childImpostor.parent = mainImpostor;
  77673. childImpostor.resetUpdateFlags();
  77674. 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));
  77675. //Add the mass of the children.
  77676. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  77677. }
  77678. }
  77679. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  77680. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  77681. };
  77682. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  77683. }
  77684. };
  77685. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  77686. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  77687. this.world.removeEventListener("preStep", impostor.beforeStep);
  77688. this.world.removeEventListener("postStep", impostor.afterStep);
  77689. this.world.remove(impostor.physicsBody);
  77690. };
  77691. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  77692. var mainBody = impostorJoint.mainImpostor.physicsBody;
  77693. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  77694. if (!mainBody || !connectedBody) {
  77695. return;
  77696. }
  77697. var constraint;
  77698. var jointData = impostorJoint.joint.jointData;
  77699. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  77700. var constraintData = {
  77701. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  77702. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  77703. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  77704. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  77705. maxForce: jointData.nativeParams.maxForce,
  77706. collideConnected: !!jointData.collision
  77707. };
  77708. switch (impostorJoint.joint.type) {
  77709. case BABYLON.PhysicsJoint.HingeJoint:
  77710. case BABYLON.PhysicsJoint.Hinge2Joint:
  77711. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  77712. break;
  77713. case BABYLON.PhysicsJoint.DistanceJoint:
  77714. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  77715. break;
  77716. case BABYLON.PhysicsJoint.SpringJoint:
  77717. var springData = jointData;
  77718. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  77719. restLength: springData.length,
  77720. stiffness: springData.stiffness,
  77721. damping: springData.damping,
  77722. localAnchorA: constraintData.pivotA,
  77723. localAnchorB: constraintData.pivotB
  77724. });
  77725. break;
  77726. case BABYLON.PhysicsJoint.LockJoint:
  77727. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  77728. break;
  77729. case BABYLON.PhysicsJoint.PointToPointJoint:
  77730. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  77731. default:
  77732. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  77733. break;
  77734. }
  77735. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  77736. constraint.collideConnected = !!jointData.collision;
  77737. impostorJoint.joint.physicsJoint = constraint;
  77738. //don't add spring as constraint, as it is not one.
  77739. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  77740. this.world.addConstraint(constraint);
  77741. }
  77742. else {
  77743. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  77744. constraint.applyForce();
  77745. });
  77746. }
  77747. };
  77748. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  77749. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  77750. };
  77751. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  77752. var index;
  77753. var mat;
  77754. for (index = 0; index < this._physicsMaterials.length; index++) {
  77755. mat = this._physicsMaterials[index];
  77756. if (mat.friction === friction && mat.restitution === restitution) {
  77757. return mat;
  77758. }
  77759. }
  77760. var currentMat = new this.BJSCANNON.Material(name);
  77761. currentMat.friction = friction;
  77762. currentMat.restitution = restitution;
  77763. this._physicsMaterials.push(currentMat);
  77764. return currentMat;
  77765. };
  77766. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  77767. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  77768. };
  77769. CannonJSPlugin.prototype._createShape = function (impostor) {
  77770. var object = impostor.object;
  77771. var returnValue;
  77772. var extendSize = impostor.getObjectExtendSize();
  77773. switch (impostor.type) {
  77774. case BABYLON.PhysicsImpostor.SphereImpostor:
  77775. var radiusX = extendSize.x;
  77776. var radiusY = extendSize.y;
  77777. var radiusZ = extendSize.z;
  77778. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  77779. break;
  77780. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  77781. case BABYLON.PhysicsImpostor.CylinderImpostor:
  77782. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  77783. break;
  77784. case BABYLON.PhysicsImpostor.BoxImpostor:
  77785. var box = extendSize.scale(0.5);
  77786. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  77787. break;
  77788. case BABYLON.PhysicsImpostor.PlaneImpostor:
  77789. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  77790. returnValue = new this.BJSCANNON.Plane();
  77791. break;
  77792. case BABYLON.PhysicsImpostor.MeshImpostor:
  77793. // should transform the vertex data to world coordinates!!
  77794. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  77795. var rawFaces = object.getIndices ? object.getIndices() : [];
  77796. if (!rawVerts)
  77797. return;
  77798. // get only scale! so the object could transform correctly.
  77799. var oldPosition = object.position.clone();
  77800. var oldRotation = object.rotation && object.rotation.clone();
  77801. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  77802. object.position.copyFromFloats(0, 0, 0);
  77803. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77804. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77805. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77806. var transform = object.computeWorldMatrix(true);
  77807. // convert rawVerts to object space
  77808. var temp = new Array();
  77809. var index;
  77810. for (index = 0; index < rawVerts.length; index += 3) {
  77811. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  77812. }
  77813. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  77814. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  77815. //now set back the transformation!
  77816. object.position.copyFrom(oldPosition);
  77817. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  77818. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  77819. break;
  77820. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  77821. var oldPosition2 = object.position.clone();
  77822. var oldRotation2 = object.rotation && object.rotation.clone();
  77823. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  77824. object.position.copyFromFloats(0, 0, 0);
  77825. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  77826. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  77827. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  77828. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  77829. returnValue = this._createHeightmap(object);
  77830. object.position.copyFrom(oldPosition2);
  77831. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  77832. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  77833. object.computeWorldMatrix(true);
  77834. break;
  77835. case BABYLON.PhysicsImpostor.ParticleImpostor:
  77836. returnValue = new this.BJSCANNON.Particle();
  77837. break;
  77838. }
  77839. return returnValue;
  77840. };
  77841. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  77842. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77843. var transform = object.computeWorldMatrix(true);
  77844. // convert rawVerts to object space
  77845. var temp = new Array();
  77846. var index;
  77847. for (index = 0; index < pos.length; index += 3) {
  77848. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  77849. }
  77850. pos = temp;
  77851. var matrix = new Array();
  77852. //For now pointDepth will not be used and will be automatically calculated.
  77853. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  77854. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  77855. var boundingInfo = object.getBoundingInfo();
  77856. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  77857. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  77858. var elementSize = dim * 2 / arraySize;
  77859. for (var i = 0; i < pos.length; i = i + 3) {
  77860. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  77861. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  77862. var y = -pos[i + 2] + minY;
  77863. if (!matrix[x]) {
  77864. matrix[x] = [];
  77865. }
  77866. if (!matrix[x][z]) {
  77867. matrix[x][z] = y;
  77868. }
  77869. matrix[x][z] = Math.max(y, matrix[x][z]);
  77870. }
  77871. for (var x = 0; x <= arraySize; ++x) {
  77872. if (!matrix[x]) {
  77873. var loc = 1;
  77874. while (!matrix[(x + loc) % arraySize]) {
  77875. loc++;
  77876. }
  77877. matrix[x] = matrix[(x + loc) % arraySize].slice();
  77878. //console.log("missing x", x);
  77879. }
  77880. for (var z = 0; z <= arraySize; ++z) {
  77881. if (!matrix[x][z]) {
  77882. var loc = 1;
  77883. var newValue;
  77884. while (newValue === undefined) {
  77885. newValue = matrix[x][(z + loc++) % arraySize];
  77886. }
  77887. matrix[x][z] = newValue;
  77888. }
  77889. }
  77890. }
  77891. var shape = new this.BJSCANNON.Heightfield(matrix, {
  77892. elementSize: elementSize
  77893. });
  77894. //For future reference, needed for body transformation
  77895. shape.minY = minY;
  77896. return shape;
  77897. };
  77898. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  77899. var object = impostor.object;
  77900. //make sure it is updated...
  77901. object.computeWorldMatrix && object.computeWorldMatrix(true);
  77902. // The delta between the mesh position and the mesh bounding box center
  77903. var bInfo = object.getBoundingInfo();
  77904. if (!bInfo)
  77905. return;
  77906. var center = impostor.getObjectCenter();
  77907. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  77908. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  77909. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  77910. this._tmpPosition.copyFrom(center);
  77911. var quaternion = object.rotationQuaternion;
  77912. if (!quaternion) {
  77913. return;
  77914. }
  77915. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  77916. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  77917. //-90 DEG in X, precalculated
  77918. quaternion = quaternion.multiply(this._minus90X);
  77919. //Invert! (Precalculated, 90 deg in X)
  77920. //No need to clone. this will never change.
  77921. impostor.setDeltaRotation(this._plus90X);
  77922. }
  77923. //If it is a heightfield, if should be centered.
  77924. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  77925. var mesh = object;
  77926. var boundingInfo = mesh.getBoundingInfo();
  77927. //calculate the correct body position:
  77928. var rotationQuaternion = mesh.rotationQuaternion;
  77929. mesh.rotationQuaternion = this._tmpUnityRotation;
  77930. mesh.computeWorldMatrix(true);
  77931. //get original center with no rotation
  77932. var c = center.clone();
  77933. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  77934. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  77935. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  77936. mesh.setPreTransformMatrix(p);
  77937. mesh.computeWorldMatrix(true);
  77938. //calculate the translation
  77939. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  77940. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  77941. //add it inverted to the delta
  77942. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  77943. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  77944. //rotation is back
  77945. mesh.rotationQuaternion = rotationQuaternion;
  77946. mesh.setPreTransformMatrix(oldPivot);
  77947. mesh.computeWorldMatrix(true);
  77948. }
  77949. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  77950. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  77951. //this._tmpPosition.copyFrom(object.position);
  77952. }
  77953. impostor.setDeltaPosition(this._tmpDeltaPosition);
  77954. //Now update the impostor object
  77955. impostor.physicsBody.position.copy(this._tmpPosition);
  77956. impostor.physicsBody.quaternion.copy(quaternion);
  77957. };
  77958. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  77959. impostor.object.position.copyFrom(impostor.physicsBody.position);
  77960. if (impostor.object.rotationQuaternion) {
  77961. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  77962. }
  77963. };
  77964. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  77965. impostor.physicsBody.position.copy(newPosition);
  77966. impostor.physicsBody.quaternion.copy(newRotation);
  77967. };
  77968. CannonJSPlugin.prototype.isSupported = function () {
  77969. return this.BJSCANNON !== undefined;
  77970. };
  77971. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  77972. impostor.physicsBody.velocity.copy(velocity);
  77973. };
  77974. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  77975. impostor.physicsBody.angularVelocity.copy(velocity);
  77976. };
  77977. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  77978. var v = impostor.physicsBody.velocity;
  77979. if (!v) {
  77980. return null;
  77981. }
  77982. return new BABYLON.Vector3(v.x, v.y, v.z);
  77983. };
  77984. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  77985. var v = impostor.physicsBody.angularVelocity;
  77986. if (!v) {
  77987. return null;
  77988. }
  77989. return new BABYLON.Vector3(v.x, v.y, v.z);
  77990. };
  77991. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  77992. impostor.physicsBody.mass = mass;
  77993. impostor.physicsBody.updateMassProperties();
  77994. };
  77995. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  77996. return impostor.physicsBody.mass;
  77997. };
  77998. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  77999. return impostor.physicsBody.material.friction;
  78000. };
  78001. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78002. impostor.physicsBody.material.friction = friction;
  78003. };
  78004. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78005. return impostor.physicsBody.material.restitution;
  78006. };
  78007. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78008. impostor.physicsBody.material.restitution = restitution;
  78009. };
  78010. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  78011. impostor.physicsBody.sleep();
  78012. };
  78013. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  78014. impostor.physicsBody.wakeUp();
  78015. };
  78016. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78017. joint.physicsJoint.distance = maxDistance;
  78018. };
  78019. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78020. // if (!motorIndex) {
  78021. // joint.physicsJoint.enableMotor();
  78022. // }
  78023. // }
  78024. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78025. // if (!motorIndex) {
  78026. // joint.physicsJoint.disableMotor();
  78027. // }
  78028. // }
  78029. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78030. if (!motorIndex) {
  78031. joint.physicsJoint.enableMotor();
  78032. joint.physicsJoint.setMotorSpeed(speed);
  78033. if (maxForce) {
  78034. this.setLimit(joint, maxForce);
  78035. }
  78036. }
  78037. };
  78038. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  78039. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  78040. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  78041. };
  78042. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78043. var body = impostor.physicsBody;
  78044. mesh.position.x = body.position.x;
  78045. mesh.position.y = body.position.y;
  78046. mesh.position.z = body.position.z;
  78047. if (mesh.rotationQuaternion) {
  78048. mesh.rotationQuaternion.x = body.quaternion.x;
  78049. mesh.rotationQuaternion.y = body.quaternion.y;
  78050. mesh.rotationQuaternion.z = body.quaternion.z;
  78051. mesh.rotationQuaternion.w = body.quaternion.w;
  78052. }
  78053. };
  78054. CannonJSPlugin.prototype.getRadius = function (impostor) {
  78055. var shape = impostor.physicsBody.shapes[0];
  78056. return shape.boundingSphereRadius;
  78057. };
  78058. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78059. var shape = impostor.physicsBody.shapes[0];
  78060. result.x = shape.halfExtents.x * 2;
  78061. result.y = shape.halfExtents.y * 2;
  78062. result.z = shape.halfExtents.z * 2;
  78063. };
  78064. CannonJSPlugin.prototype.dispose = function () {
  78065. };
  78066. CannonJSPlugin.prototype._extendNamespace = function () {
  78067. //this will force cannon to execute at least one step when using interpolation
  78068. var step_tmp1 = new this.BJSCANNON.Vec3();
  78069. var Engine = this.BJSCANNON;
  78070. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  78071. maxSubSteps = maxSubSteps || 10;
  78072. timeSinceLastCalled = timeSinceLastCalled || 0;
  78073. if (timeSinceLastCalled === 0) {
  78074. this.internalStep(dt);
  78075. this.time += dt;
  78076. }
  78077. else {
  78078. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  78079. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  78080. var t0 = performance.now();
  78081. for (var i = 0; i !== internalSteps; i++) {
  78082. this.internalStep(dt);
  78083. if (performance.now() - t0 > dt * 1000) {
  78084. break;
  78085. }
  78086. }
  78087. this.time += timeSinceLastCalled;
  78088. var h = this.time % dt;
  78089. var h_div_dt = h / dt;
  78090. var interpvelo = step_tmp1;
  78091. var bodies = this.bodies;
  78092. for (var j = 0; j !== bodies.length; j++) {
  78093. var b = bodies[j];
  78094. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  78095. b.position.vsub(b.previousPosition, interpvelo);
  78096. interpvelo.scale(h_div_dt, interpvelo);
  78097. b.position.vadd(interpvelo, b.interpolatedPosition);
  78098. }
  78099. else {
  78100. b.interpolatedPosition.copy(b.position);
  78101. b.interpolatedQuaternion.copy(b.quaternion);
  78102. }
  78103. }
  78104. }
  78105. };
  78106. };
  78107. return CannonJSPlugin;
  78108. }());
  78109. BABYLON.CannonJSPlugin = CannonJSPlugin;
  78110. })(BABYLON || (BABYLON = {}));
  78111. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  78112. "use strict";
  78113. var BABYLON;
  78114. (function (BABYLON) {
  78115. var OimoJSPlugin = /** @class */ (function () {
  78116. function OimoJSPlugin(iterations) {
  78117. this.name = "OimoJSPlugin";
  78118. this._tmpImpostorsArray = [];
  78119. this._tmpPositionVector = BABYLON.Vector3.Zero();
  78120. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  78121. this.world = new this.BJSOIMO.World({
  78122. iterations: iterations
  78123. });
  78124. this.world.clear();
  78125. }
  78126. OimoJSPlugin.prototype.setGravity = function (gravity) {
  78127. this.world.gravity.copy(gravity);
  78128. };
  78129. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  78130. this.world.timeStep = timeStep;
  78131. };
  78132. OimoJSPlugin.prototype.getTimeStep = function () {
  78133. return this.world.timeStep;
  78134. };
  78135. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  78136. var _this = this;
  78137. impostors.forEach(function (impostor) {
  78138. impostor.beforeStep();
  78139. });
  78140. this.world.step();
  78141. impostors.forEach(function (impostor) {
  78142. impostor.afterStep();
  78143. //update the ordered impostors array
  78144. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  78145. });
  78146. //check for collisions
  78147. var contact = this.world.contacts;
  78148. while (contact !== null) {
  78149. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78150. contact = contact.next;
  78151. continue;
  78152. }
  78153. //is this body colliding with any other? get the impostor
  78154. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78155. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78156. if (!mainImpostor || !collidingImpostor) {
  78157. contact = contact.next;
  78158. continue;
  78159. }
  78160. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78161. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78162. contact = contact.next;
  78163. }
  78164. };
  78165. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78166. var mass = impostor.physicsBody.mass;
  78167. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  78168. };
  78169. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78170. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78171. this.applyImpulse(impostor, force, contactPoint);
  78172. };
  78173. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78174. var _this = this;
  78175. //parent-child relationship. Does this impostor has a parent impostor?
  78176. if (impostor.parent) {
  78177. if (impostor.physicsBody) {
  78178. this.removePhysicsBody(impostor);
  78179. //TODO is that needed?
  78180. impostor.forceUpdate();
  78181. }
  78182. return;
  78183. }
  78184. if (impostor.isBodyInitRequired()) {
  78185. var bodyConfig = {
  78186. name: impostor.uniqueId,
  78187. //Oimo must have mass, also for static objects.
  78188. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78189. size: [],
  78190. type: [],
  78191. pos: [],
  78192. posShape: [],
  78193. rot: [],
  78194. rotShape: [],
  78195. move: impostor.getParam("mass") !== 0,
  78196. density: impostor.getParam("mass"),
  78197. friction: impostor.getParam("friction"),
  78198. restitution: impostor.getParam("restitution"),
  78199. //Supporting older versions of Oimo
  78200. world: this.world
  78201. };
  78202. var impostors = [impostor];
  78203. var addToArray = function (parent) {
  78204. if (!parent.getChildMeshes)
  78205. return;
  78206. parent.getChildMeshes().forEach(function (m) {
  78207. if (m.physicsImpostor) {
  78208. impostors.push(m.physicsImpostor);
  78209. //m.physicsImpostor._init();
  78210. }
  78211. });
  78212. };
  78213. addToArray(impostor.object);
  78214. var checkWithEpsilon_1 = function (value) {
  78215. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78216. };
  78217. impostors.forEach(function (i) {
  78218. if (!i.object.rotationQuaternion) {
  78219. return;
  78220. }
  78221. //get the correct bounding box
  78222. var oldQuaternion = i.object.rotationQuaternion;
  78223. var rot = oldQuaternion.toEulerAngles();
  78224. var extendSize = i.getObjectExtendSize();
  78225. var radToDeg = 57.295779513082320876;
  78226. if (i === impostor) {
  78227. var center = impostor.getObjectCenter();
  78228. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  78229. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  78230. //Can also use Array.prototype.push.apply
  78231. bodyConfig.pos.push(center.x);
  78232. bodyConfig.pos.push(center.y);
  78233. bodyConfig.pos.push(center.z);
  78234. bodyConfig.posShape.push(0, 0, 0);
  78235. //tmp solution
  78236. bodyConfig.rot.push(rot.x * radToDeg);
  78237. bodyConfig.rot.push(rot.y * radToDeg);
  78238. bodyConfig.rot.push(rot.z * radToDeg);
  78239. bodyConfig.rotShape.push(0, 0, 0);
  78240. }
  78241. else {
  78242. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  78243. bodyConfig.posShape.push(localPosition.x);
  78244. bodyConfig.posShape.push(localPosition.y);
  78245. bodyConfig.posShape.push(localPosition.z);
  78246. bodyConfig.pos.push(0, 0, 0);
  78247. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  78248. bodyConfig.rot.push(0);
  78249. bodyConfig.rot.push(0);
  78250. bodyConfig.rot.push(0);
  78251. bodyConfig.rotShape.push(rot.x * radToDeg);
  78252. bodyConfig.rotShape.push(rot.y * radToDeg);
  78253. bodyConfig.rotShape.push(rot.z * radToDeg);
  78254. }
  78255. // register mesh
  78256. switch (i.type) {
  78257. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78258. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  78259. case BABYLON.PhysicsImpostor.SphereImpostor:
  78260. var radiusX = extendSize.x;
  78261. var radiusY = extendSize.y;
  78262. var radiusZ = extendSize.z;
  78263. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  78264. bodyConfig.type.push('sphere');
  78265. //due to the way oimo works with compounds, add 3 times
  78266. bodyConfig.size.push(size);
  78267. bodyConfig.size.push(size);
  78268. bodyConfig.size.push(size);
  78269. break;
  78270. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78271. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  78272. var sizeY = checkWithEpsilon_1(extendSize.y);
  78273. bodyConfig.type.push('cylinder');
  78274. bodyConfig.size.push(sizeX);
  78275. bodyConfig.size.push(sizeY);
  78276. //due to the way oimo works with compounds, add one more value.
  78277. bodyConfig.size.push(sizeY);
  78278. break;
  78279. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78280. case BABYLON.PhysicsImpostor.BoxImpostor:
  78281. default:
  78282. var sizeX = checkWithEpsilon_1(extendSize.x);
  78283. var sizeY = checkWithEpsilon_1(extendSize.y);
  78284. var sizeZ = checkWithEpsilon_1(extendSize.z);
  78285. bodyConfig.type.push('box');
  78286. //if (i === impostor) {
  78287. bodyConfig.size.push(sizeX);
  78288. bodyConfig.size.push(sizeY);
  78289. bodyConfig.size.push(sizeZ);
  78290. //} else {
  78291. // bodyConfig.size.push(0,0,0);
  78292. //}
  78293. break;
  78294. }
  78295. //actually not needed, but hey...
  78296. i.object.rotationQuaternion = oldQuaternion;
  78297. });
  78298. impostor.physicsBody = this.world.add(bodyConfig);
  78299. }
  78300. else {
  78301. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  78302. }
  78303. impostor.setDeltaPosition(this._tmpPositionVector);
  78304. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  78305. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  78306. };
  78307. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78308. //impostor.physicsBody.dispose();
  78309. //Same as : (older oimo versions)
  78310. this.world.removeRigidBody(impostor.physicsBody);
  78311. };
  78312. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78313. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78314. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78315. if (!mainBody || !connectedBody) {
  78316. return;
  78317. }
  78318. var jointData = impostorJoint.joint.jointData;
  78319. var options = jointData.nativeParams || {};
  78320. var type;
  78321. var nativeJointData = {
  78322. body1: mainBody,
  78323. body2: connectedBody,
  78324. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  78325. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  78326. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  78327. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  78328. min: options.min,
  78329. max: options.max,
  78330. collision: options.collision || jointData.collision,
  78331. spring: options.spring,
  78332. //supporting older version of Oimo
  78333. world: this.world
  78334. };
  78335. switch (impostorJoint.joint.type) {
  78336. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78337. type = "jointBall";
  78338. break;
  78339. case BABYLON.PhysicsJoint.SpringJoint:
  78340. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  78341. var springData = jointData;
  78342. nativeJointData.min = springData.length || nativeJointData.min;
  78343. //Max should also be set, just make sure it is at least min
  78344. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  78345. case BABYLON.PhysicsJoint.DistanceJoint:
  78346. type = "jointDistance";
  78347. nativeJointData.max = jointData.maxDistance;
  78348. break;
  78349. case BABYLON.PhysicsJoint.PrismaticJoint:
  78350. type = "jointPrisme";
  78351. break;
  78352. case BABYLON.PhysicsJoint.SliderJoint:
  78353. type = "jointSlide";
  78354. break;
  78355. case BABYLON.PhysicsJoint.WheelJoint:
  78356. type = "jointWheel";
  78357. break;
  78358. case BABYLON.PhysicsJoint.HingeJoint:
  78359. default:
  78360. type = "jointHinge";
  78361. break;
  78362. }
  78363. nativeJointData.type = type;
  78364. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  78365. };
  78366. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78367. //Bug in Oimo prevents us from disposing a joint in the playground
  78368. //joint.joint.physicsJoint.dispose();
  78369. //So we will bruteforce it!
  78370. try {
  78371. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  78372. }
  78373. catch (e) {
  78374. BABYLON.Tools.Warn(e);
  78375. }
  78376. };
  78377. OimoJSPlugin.prototype.isSupported = function () {
  78378. return this.BJSOIMO !== undefined;
  78379. };
  78380. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78381. if (!impostor.physicsBody.sleeping) {
  78382. //TODO check that
  78383. /*if (impostor.physicsBody.shapes.next) {
  78384. var parentShape = this._getLastShape(impostor.physicsBody);
  78385. impostor.object.position.copyFrom(parentShape.position);
  78386. console.log(parentShape.position);
  78387. } else {*/
  78388. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  78389. //}
  78390. if (impostor.object.rotationQuaternion) {
  78391. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  78392. }
  78393. }
  78394. };
  78395. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78396. var body = impostor.physicsBody;
  78397. body.position.copy(newPosition);
  78398. body.orientation.copy(newRotation);
  78399. body.syncShapes();
  78400. body.awake();
  78401. };
  78402. /*private _getLastShape(body: any): any {
  78403. var lastShape = body.shapes;
  78404. while (lastShape.next) {
  78405. lastShape = lastShape.next;
  78406. }
  78407. return lastShape;
  78408. }*/
  78409. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78410. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  78411. };
  78412. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78413. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  78414. };
  78415. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78416. var v = impostor.physicsBody.linearVelocity;
  78417. if (!v) {
  78418. return null;
  78419. }
  78420. return new BABYLON.Vector3(v.x, v.y, v.z);
  78421. };
  78422. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78423. var v = impostor.physicsBody.angularVelocity;
  78424. if (!v) {
  78425. return null;
  78426. }
  78427. return new BABYLON.Vector3(v.x, v.y, v.z);
  78428. };
  78429. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78430. var staticBody = mass === 0;
  78431. //this will actually set the body's density and not its mass.
  78432. //But this is how oimo treats the mass variable.
  78433. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  78434. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  78435. };
  78436. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  78437. return impostor.physicsBody.shapes.density;
  78438. };
  78439. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  78440. return impostor.physicsBody.shapes.friction;
  78441. };
  78442. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78443. impostor.physicsBody.shapes.friction = friction;
  78444. };
  78445. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78446. return impostor.physicsBody.shapes.restitution;
  78447. };
  78448. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78449. impostor.physicsBody.shapes.restitution = restitution;
  78450. };
  78451. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  78452. impostor.physicsBody.sleep();
  78453. };
  78454. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  78455. impostor.physicsBody.awake();
  78456. };
  78457. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78458. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  78459. if (minDistance !== void 0) {
  78460. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  78461. }
  78462. };
  78463. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78464. //TODO separate rotational and transational motors.
  78465. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78466. if (motor) {
  78467. motor.setMotor(speed, maxForce);
  78468. }
  78469. };
  78470. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  78471. //TODO separate rotational and transational motors.
  78472. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  78473. if (motor) {
  78474. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  78475. }
  78476. };
  78477. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78478. var body = impostor.physicsBody;
  78479. mesh.position.x = body.position.x;
  78480. mesh.position.y = body.position.y;
  78481. mesh.position.z = body.position.z;
  78482. if (mesh.rotationQuaternion) {
  78483. mesh.rotationQuaternion.x = body.orientation.x;
  78484. mesh.rotationQuaternion.y = body.orientation.y;
  78485. mesh.rotationQuaternion.z = body.orientation.z;
  78486. mesh.rotationQuaternion.w = body.orientation.s;
  78487. }
  78488. };
  78489. OimoJSPlugin.prototype.getRadius = function (impostor) {
  78490. return impostor.physicsBody.shapes.radius;
  78491. };
  78492. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78493. var shape = impostor.physicsBody.shapes;
  78494. result.x = shape.halfWidth * 2;
  78495. result.y = shape.halfHeight * 2;
  78496. result.z = shape.halfDepth * 2;
  78497. };
  78498. OimoJSPlugin.prototype.dispose = function () {
  78499. this.world.clear();
  78500. };
  78501. return OimoJSPlugin;
  78502. }());
  78503. BABYLON.OimoJSPlugin = OimoJSPlugin;
  78504. })(BABYLON || (BABYLON = {}));
  78505. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  78506. "use strict";
  78507. var BABYLON;
  78508. (function (BABYLON) {
  78509. /*
  78510. * Based on jsTGALoader - Javascript loader for TGA file
  78511. * By Vincent Thibault
  78512. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  78513. */
  78514. var TGATools = /** @class */ (function () {
  78515. function TGATools() {
  78516. }
  78517. TGATools.GetTGAHeader = function (data) {
  78518. var offset = 0;
  78519. var header = {
  78520. id_length: data[offset++],
  78521. colormap_type: data[offset++],
  78522. image_type: data[offset++],
  78523. colormap_index: data[offset++] | data[offset++] << 8,
  78524. colormap_length: data[offset++] | data[offset++] << 8,
  78525. colormap_size: data[offset++],
  78526. origin: [
  78527. data[offset++] | data[offset++] << 8,
  78528. data[offset++] | data[offset++] << 8
  78529. ],
  78530. width: data[offset++] | data[offset++] << 8,
  78531. height: data[offset++] | data[offset++] << 8,
  78532. pixel_size: data[offset++],
  78533. flags: data[offset++]
  78534. };
  78535. return header;
  78536. };
  78537. TGATools.UploadContent = function (gl, data) {
  78538. // Not enough data to contain header ?
  78539. if (data.length < 19) {
  78540. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  78541. return;
  78542. }
  78543. // Read Header
  78544. var offset = 18;
  78545. var header = TGATools.GetTGAHeader(data);
  78546. // Assume it's a valid Targa file.
  78547. if (header.id_length + offset > data.length) {
  78548. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  78549. return;
  78550. }
  78551. // Skip not needed data
  78552. offset += header.id_length;
  78553. var use_rle = false;
  78554. var use_pal = false;
  78555. var use_grey = false;
  78556. // Get some informations.
  78557. switch (header.image_type) {
  78558. case TGATools._TYPE_RLE_INDEXED:
  78559. use_rle = true;
  78560. case TGATools._TYPE_INDEXED:
  78561. use_pal = true;
  78562. break;
  78563. case TGATools._TYPE_RLE_RGB:
  78564. use_rle = true;
  78565. case TGATools._TYPE_RGB:
  78566. // use_rgb = true;
  78567. break;
  78568. case TGATools._TYPE_RLE_GREY:
  78569. use_rle = true;
  78570. case TGATools._TYPE_GREY:
  78571. use_grey = true;
  78572. break;
  78573. }
  78574. var pixel_data;
  78575. // var numAlphaBits = header.flags & 0xf;
  78576. var pixel_size = header.pixel_size >> 3;
  78577. var pixel_total = header.width * header.height * pixel_size;
  78578. // Read palettes
  78579. var palettes;
  78580. if (use_pal) {
  78581. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  78582. }
  78583. // Read LRE
  78584. if (use_rle) {
  78585. pixel_data = new Uint8Array(pixel_total);
  78586. var c, count, i;
  78587. var localOffset = 0;
  78588. var pixels = new Uint8Array(pixel_size);
  78589. while (offset < pixel_total && localOffset < pixel_total) {
  78590. c = data[offset++];
  78591. count = (c & 0x7f) + 1;
  78592. // RLE pixels
  78593. if (c & 0x80) {
  78594. // Bind pixel tmp array
  78595. for (i = 0; i < pixel_size; ++i) {
  78596. pixels[i] = data[offset++];
  78597. }
  78598. // Copy pixel array
  78599. for (i = 0; i < count; ++i) {
  78600. pixel_data.set(pixels, localOffset + i * pixel_size);
  78601. }
  78602. localOffset += pixel_size * count;
  78603. }
  78604. else {
  78605. count *= pixel_size;
  78606. for (i = 0; i < count; ++i) {
  78607. pixel_data[localOffset + i] = data[offset++];
  78608. }
  78609. localOffset += count;
  78610. }
  78611. }
  78612. }
  78613. else {
  78614. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  78615. }
  78616. // Load to texture
  78617. var x_start, y_start, x_step, y_step, y_end, x_end;
  78618. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  78619. default:
  78620. case TGATools._ORIGIN_UL:
  78621. x_start = 0;
  78622. x_step = 1;
  78623. x_end = header.width;
  78624. y_start = 0;
  78625. y_step = 1;
  78626. y_end = header.height;
  78627. break;
  78628. case TGATools._ORIGIN_BL:
  78629. x_start = 0;
  78630. x_step = 1;
  78631. x_end = header.width;
  78632. y_start = header.height - 1;
  78633. y_step = -1;
  78634. y_end = -1;
  78635. break;
  78636. case TGATools._ORIGIN_UR:
  78637. x_start = header.width - 1;
  78638. x_step = -1;
  78639. x_end = -1;
  78640. y_start = 0;
  78641. y_step = 1;
  78642. y_end = header.height;
  78643. break;
  78644. case TGATools._ORIGIN_BR:
  78645. x_start = header.width - 1;
  78646. x_step = -1;
  78647. x_end = -1;
  78648. y_start = header.height - 1;
  78649. y_step = -1;
  78650. y_end = -1;
  78651. break;
  78652. }
  78653. // Load the specify method
  78654. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  78655. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  78656. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  78657. };
  78658. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78659. var image = pixel_data, colormap = palettes;
  78660. var width = header.width, height = header.height;
  78661. var color, i = 0, x, y;
  78662. var imageData = new Uint8Array(width * height * 4);
  78663. for (y = y_start; y !== y_end; y += y_step) {
  78664. for (x = x_start; x !== x_end; x += x_step, i++) {
  78665. color = image[i];
  78666. imageData[(x + width * y) * 4 + 3] = 255;
  78667. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  78668. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  78669. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  78670. }
  78671. }
  78672. return imageData;
  78673. };
  78674. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78675. var image = pixel_data;
  78676. var width = header.width, height = header.height;
  78677. var color, i = 0, x, y;
  78678. var imageData = new Uint8Array(width * height * 4);
  78679. for (y = y_start; y !== y_end; y += y_step) {
  78680. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78681. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  78682. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  78683. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  78684. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  78685. imageData[(x + width * y) * 4 + 0] = r;
  78686. imageData[(x + width * y) * 4 + 1] = g;
  78687. imageData[(x + width * y) * 4 + 2] = b;
  78688. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  78689. }
  78690. }
  78691. return imageData;
  78692. };
  78693. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78694. var image = pixel_data;
  78695. var width = header.width, height = header.height;
  78696. var i = 0, x, y;
  78697. var imageData = new Uint8Array(width * height * 4);
  78698. for (y = y_start; y !== y_end; y += y_step) {
  78699. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  78700. imageData[(x + width * y) * 4 + 3] = 255;
  78701. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78702. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78703. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78704. }
  78705. }
  78706. return imageData;
  78707. };
  78708. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78709. var image = pixel_data;
  78710. var width = header.width, height = header.height;
  78711. var i = 0, x, y;
  78712. var imageData = new Uint8Array(width * height * 4);
  78713. for (y = y_start; y !== y_end; y += y_step) {
  78714. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  78715. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78716. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  78717. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  78718. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  78719. }
  78720. }
  78721. return imageData;
  78722. };
  78723. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78724. var image = pixel_data;
  78725. var width = header.width, height = header.height;
  78726. var color, i = 0, x, y;
  78727. var imageData = new Uint8Array(width * height * 4);
  78728. for (y = y_start; y !== y_end; y += y_step) {
  78729. for (x = x_start; x !== x_end; x += x_step, i++) {
  78730. color = image[i];
  78731. imageData[(x + width * y) * 4 + 0] = color;
  78732. imageData[(x + width * y) * 4 + 1] = color;
  78733. imageData[(x + width * y) * 4 + 2] = color;
  78734. imageData[(x + width * y) * 4 + 3] = 255;
  78735. }
  78736. }
  78737. return imageData;
  78738. };
  78739. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  78740. var image = pixel_data;
  78741. var width = header.width, height = header.height;
  78742. var i = 0, x, y;
  78743. var imageData = new Uint8Array(width * height * 4);
  78744. for (y = y_start; y !== y_end; y += y_step) {
  78745. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  78746. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  78747. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  78748. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  78749. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  78750. }
  78751. }
  78752. return imageData;
  78753. };
  78754. //private static _TYPE_NO_DATA = 0;
  78755. TGATools._TYPE_INDEXED = 1;
  78756. TGATools._TYPE_RGB = 2;
  78757. TGATools._TYPE_GREY = 3;
  78758. TGATools._TYPE_RLE_INDEXED = 9;
  78759. TGATools._TYPE_RLE_RGB = 10;
  78760. TGATools._TYPE_RLE_GREY = 11;
  78761. TGATools._ORIGIN_MASK = 0x30;
  78762. TGATools._ORIGIN_SHIFT = 0x04;
  78763. TGATools._ORIGIN_BL = 0x00;
  78764. TGATools._ORIGIN_BR = 0x01;
  78765. TGATools._ORIGIN_UL = 0x02;
  78766. TGATools._ORIGIN_UR = 0x03;
  78767. return TGATools;
  78768. }());
  78769. BABYLON.TGATools = TGATools;
  78770. })(BABYLON || (BABYLON = {}));
  78771. //# sourceMappingURL=babylon.tga.js.map
  78772. "use strict";
  78773. var BABYLON;
  78774. (function (BABYLON) {
  78775. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  78776. // All values and structures referenced from:
  78777. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  78778. var DDS_MAGIC = 0x20534444;
  78779. var
  78780. //DDSD_CAPS = 0x1,
  78781. //DDSD_HEIGHT = 0x2,
  78782. //DDSD_WIDTH = 0x4,
  78783. //DDSD_PITCH = 0x8,
  78784. //DDSD_PIXELFORMAT = 0x1000,
  78785. DDSD_MIPMAPCOUNT = 0x20000;
  78786. //DDSD_LINEARSIZE = 0x80000,
  78787. //DDSD_DEPTH = 0x800000;
  78788. // var DDSCAPS_COMPLEX = 0x8,
  78789. // DDSCAPS_MIPMAP = 0x400000,
  78790. // DDSCAPS_TEXTURE = 0x1000;
  78791. var DDSCAPS2_CUBEMAP = 0x200;
  78792. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  78793. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  78794. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  78795. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  78796. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  78797. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  78798. // DDSCAPS2_VOLUME = 0x200000;
  78799. var
  78800. //DDPF_ALPHAPIXELS = 0x1,
  78801. //DDPF_ALPHA = 0x2,
  78802. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  78803. //DDPF_YUV = 0x200,
  78804. DDPF_LUMINANCE = 0x20000;
  78805. function FourCCToInt32(value) {
  78806. return value.charCodeAt(0) +
  78807. (value.charCodeAt(1) << 8) +
  78808. (value.charCodeAt(2) << 16) +
  78809. (value.charCodeAt(3) << 24);
  78810. }
  78811. function Int32ToFourCC(value) {
  78812. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  78813. }
  78814. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  78815. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  78816. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  78817. var FOURCC_DX10 = FourCCToInt32("DX10");
  78818. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  78819. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  78820. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  78821. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  78822. var headerLengthInt = 31; // The header length in 32 bit ints
  78823. // Offsets into the header array
  78824. var off_magic = 0;
  78825. var off_size = 1;
  78826. var off_flags = 2;
  78827. var off_height = 3;
  78828. var off_width = 4;
  78829. var off_mipmapCount = 7;
  78830. var off_pfFlags = 20;
  78831. var off_pfFourCC = 21;
  78832. var off_RGBbpp = 22;
  78833. var off_RMask = 23;
  78834. var off_GMask = 24;
  78835. var off_BMask = 25;
  78836. var off_AMask = 26;
  78837. // var off_caps1 = 27;
  78838. var off_caps2 = 28;
  78839. // var off_caps3 = 29;
  78840. // var off_caps4 = 30;
  78841. var off_dxgiFormat = 32;
  78842. ;
  78843. var DDSTools = /** @class */ (function () {
  78844. function DDSTools() {
  78845. }
  78846. DDSTools.GetDDSInfo = function (arrayBuffer) {
  78847. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  78848. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  78849. var mipmapCount = 1;
  78850. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  78851. mipmapCount = Math.max(1, header[off_mipmapCount]);
  78852. }
  78853. var fourCC = header[off_pfFourCC];
  78854. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  78855. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78856. switch (fourCC) {
  78857. case FOURCC_D3DFMT_R16G16B16A16F:
  78858. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78859. break;
  78860. case FOURCC_D3DFMT_R32G32B32A32F:
  78861. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78862. break;
  78863. case FOURCC_DX10:
  78864. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  78865. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78866. break;
  78867. }
  78868. }
  78869. return {
  78870. width: header[off_width],
  78871. height: header[off_height],
  78872. mipmapCount: mipmapCount,
  78873. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  78874. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  78875. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  78876. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  78877. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  78878. dxgiFormat: dxgiFormat,
  78879. textureType: textureType
  78880. };
  78881. };
  78882. DDSTools._ToHalfFloat = function (value) {
  78883. if (!DDSTools._FloatView) {
  78884. DDSTools._FloatView = new Float32Array(1);
  78885. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  78886. }
  78887. DDSTools._FloatView[0] = value;
  78888. var x = DDSTools._Int32View[0];
  78889. var bits = (x >> 16) & 0x8000; /* Get the sign */
  78890. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  78891. var e = (x >> 23) & 0xff; /* Using int is faster here */
  78892. /* If zero, or denormal, or exponent underflows too much for a denormal
  78893. * half, return signed zero. */
  78894. if (e < 103) {
  78895. return bits;
  78896. }
  78897. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  78898. if (e > 142) {
  78899. bits |= 0x7c00;
  78900. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  78901. * not Inf, so make sure we set one mantissa bit too. */
  78902. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  78903. return bits;
  78904. }
  78905. /* If exponent underflows but not too much, return a denormal */
  78906. if (e < 113) {
  78907. m |= 0x0800;
  78908. /* Extra rounding may overflow and set mantissa to 0 and exponent
  78909. * to 1, which is OK. */
  78910. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  78911. return bits;
  78912. }
  78913. bits |= ((e - 112) << 10) | (m >> 1);
  78914. bits += m & 1;
  78915. return bits;
  78916. };
  78917. DDSTools._FromHalfFloat = function (value) {
  78918. var s = (value & 0x8000) >> 15;
  78919. var e = (value & 0x7C00) >> 10;
  78920. var f = value & 0x03FF;
  78921. if (e === 0) {
  78922. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  78923. }
  78924. else if (e == 0x1F) {
  78925. return f ? NaN : ((s ? -1 : 1) * Infinity);
  78926. }
  78927. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  78928. };
  78929. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78930. var destArray = new Float32Array(dataLength);
  78931. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78932. var index = 0;
  78933. for (var y = 0; y < height; y++) {
  78934. for (var x = 0; x < width; x++) {
  78935. var srcPos = (x + y * width) * 4;
  78936. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  78937. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  78938. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  78939. if (DDSTools.StoreLODInAlphaChannel) {
  78940. destArray[index + 3] = lod;
  78941. }
  78942. else {
  78943. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  78944. }
  78945. index += 4;
  78946. }
  78947. }
  78948. return destArray;
  78949. };
  78950. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78951. if (DDSTools.StoreLODInAlphaChannel) {
  78952. var destArray = new Uint16Array(dataLength);
  78953. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  78954. var index = 0;
  78955. for (var y = 0; y < height; y++) {
  78956. for (var x = 0; x < width; x++) {
  78957. var srcPos = (x + y * width) * 4;
  78958. destArray[index] = srcData[srcPos];
  78959. destArray[index + 1] = srcData[srcPos + 1];
  78960. destArray[index + 2] = srcData[srcPos + 2];
  78961. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  78962. index += 4;
  78963. }
  78964. }
  78965. return destArray;
  78966. }
  78967. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  78968. };
  78969. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78970. if (DDSTools.StoreLODInAlphaChannel) {
  78971. var destArray = new Float32Array(dataLength);
  78972. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78973. var index = 0;
  78974. for (var y = 0; y < height; y++) {
  78975. for (var x = 0; x < width; x++) {
  78976. var srcPos = (x + y * width) * 4;
  78977. destArray[index] = srcData[srcPos];
  78978. destArray[index + 1] = srcData[srcPos + 1];
  78979. destArray[index + 2] = srcData[srcPos + 2];
  78980. destArray[index + 3] = lod;
  78981. index += 4;
  78982. }
  78983. }
  78984. return destArray;
  78985. }
  78986. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  78987. };
  78988. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  78989. var destArray = new Uint8Array(dataLength);
  78990. var srcData = new Float32Array(arrayBuffer, dataOffset);
  78991. var index = 0;
  78992. for (var y = 0; y < height; y++) {
  78993. for (var x = 0; x < width; x++) {
  78994. var srcPos = (x + y * width) * 4;
  78995. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  78996. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  78997. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  78998. if (DDSTools.StoreLODInAlphaChannel) {
  78999. destArray[index + 3] = lod;
  79000. }
  79001. else {
  79002. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  79003. }
  79004. index += 4;
  79005. }
  79006. }
  79007. return destArray;
  79008. };
  79009. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79010. var destArray = new Uint8Array(dataLength);
  79011. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79012. var index = 0;
  79013. for (var y = 0; y < height; y++) {
  79014. for (var x = 0; x < width; x++) {
  79015. var srcPos = (x + y * width) * 4;
  79016. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  79017. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  79018. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  79019. if (DDSTools.StoreLODInAlphaChannel) {
  79020. destArray[index + 3] = lod;
  79021. }
  79022. else {
  79023. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  79024. }
  79025. index += 4;
  79026. }
  79027. }
  79028. return destArray;
  79029. };
  79030. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  79031. var byteArray = new Uint8Array(dataLength);
  79032. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79033. var index = 0;
  79034. for (var y = 0; y < height; y++) {
  79035. for (var x = 0; x < width; x++) {
  79036. var srcPos = (x + y * width) * 4;
  79037. byteArray[index] = srcData[srcPos + rOffset];
  79038. byteArray[index + 1] = srcData[srcPos + gOffset];
  79039. byteArray[index + 2] = srcData[srcPos + bOffset];
  79040. byteArray[index + 3] = srcData[srcPos + aOffset];
  79041. index += 4;
  79042. }
  79043. }
  79044. return byteArray;
  79045. };
  79046. DDSTools._ExtractLongWordOrder = function (value) {
  79047. if (value === 0 || value === 255 || value === -16777216) {
  79048. return 0;
  79049. }
  79050. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  79051. };
  79052. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  79053. var byteArray = new Uint8Array(dataLength);
  79054. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79055. var index = 0;
  79056. for (var y = 0; y < height; y++) {
  79057. for (var x = 0; x < width; x++) {
  79058. var srcPos = (x + y * width) * 3;
  79059. byteArray[index] = srcData[srcPos + rOffset];
  79060. byteArray[index + 1] = srcData[srcPos + gOffset];
  79061. byteArray[index + 2] = srcData[srcPos + bOffset];
  79062. index += 3;
  79063. }
  79064. }
  79065. return byteArray;
  79066. };
  79067. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  79068. var byteArray = new Uint8Array(dataLength);
  79069. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79070. var index = 0;
  79071. for (var y = 0; y < height; y++) {
  79072. for (var x = 0; x < width; x++) {
  79073. var srcPos = (x + y * width);
  79074. byteArray[index] = srcData[srcPos];
  79075. index++;
  79076. }
  79077. }
  79078. return byteArray;
  79079. };
  79080. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  79081. if (lodIndex === void 0) { lodIndex = -1; }
  79082. var ext = engine.getCaps().s3tc;
  79083. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79084. var fourCC, width, height, dataLength = 0, dataOffset;
  79085. var byteArray, mipmapCount, mip;
  79086. var internalFormat = 0;
  79087. var format = 0;
  79088. var blockBytes = 1;
  79089. if (header[off_magic] !== DDS_MAGIC) {
  79090. BABYLON.Tools.Error("Invalid magic number in DDS header");
  79091. return;
  79092. }
  79093. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  79094. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  79095. return;
  79096. }
  79097. if (info.isCompressed && !ext) {
  79098. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  79099. return;
  79100. }
  79101. var bpp = header[off_RGBbpp];
  79102. dataOffset = header[off_size] + 4;
  79103. var computeFormats = false;
  79104. if (info.isFourCC) {
  79105. fourCC = header[off_pfFourCC];
  79106. switch (fourCC) {
  79107. case FOURCC_DXT1:
  79108. blockBytes = 8;
  79109. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  79110. break;
  79111. case FOURCC_DXT3:
  79112. blockBytes = 16;
  79113. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  79114. break;
  79115. case FOURCC_DXT5:
  79116. blockBytes = 16;
  79117. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  79118. break;
  79119. case FOURCC_D3DFMT_R16G16B16A16F:
  79120. computeFormats = true;
  79121. break;
  79122. case FOURCC_D3DFMT_R32G32B32A32F:
  79123. computeFormats = true;
  79124. break;
  79125. case FOURCC_DX10:
  79126. // There is an additionnal header so dataOffset need to be changed
  79127. dataOffset += 5 * 4; // 5 uints
  79128. var supported = false;
  79129. switch (info.dxgiFormat) {
  79130. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  79131. computeFormats = true;
  79132. supported = true;
  79133. break;
  79134. case DXGI_FORMAT_B8G8R8X8_UNORM:
  79135. info.isRGB = true;
  79136. info.isFourCC = false;
  79137. bpp = 32;
  79138. supported = true;
  79139. break;
  79140. }
  79141. if (supported) {
  79142. break;
  79143. }
  79144. default:
  79145. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  79146. return;
  79147. }
  79148. }
  79149. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  79150. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  79151. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  79152. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  79153. if (computeFormats) {
  79154. format = engine._getWebGLTextureType(info.textureType);
  79155. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79156. }
  79157. mipmapCount = 1;
  79158. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79159. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79160. }
  79161. for (var face = 0; face < faces; face++) {
  79162. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79163. width = header[off_width];
  79164. height = header[off_height];
  79165. for (mip = 0; mip < mipmapCount; ++mip) {
  79166. if (lodIndex === -1 || lodIndex === mip) {
  79167. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79168. var i = (lodIndex === -1) ? mip : 0;
  79169. if (!info.isCompressed && info.isFourCC) {
  79170. dataLength = width * height * 4;
  79171. var floatArray = null;
  79172. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79173. if (bpp === 128) {
  79174. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79175. }
  79176. else if (bpp === 64) {
  79177. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79178. }
  79179. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79180. format = engine._getWebGLTextureType(info.textureType);
  79181. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79182. }
  79183. else {
  79184. if (bpp === 128) {
  79185. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79186. }
  79187. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79188. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79189. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79190. format = engine._getWebGLTextureType(info.textureType);
  79191. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79192. }
  79193. else {
  79194. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79195. }
  79196. }
  79197. if (floatArray) {
  79198. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79199. }
  79200. }
  79201. else if (info.isRGB) {
  79202. if (bpp === 24) {
  79203. dataLength = width * height * 3;
  79204. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79205. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79206. }
  79207. else {
  79208. dataLength = width * height * 4;
  79209. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79210. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79211. }
  79212. }
  79213. else if (info.isLuminance) {
  79214. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79215. var unpaddedRowSize = width;
  79216. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79217. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79218. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79219. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79220. }
  79221. else {
  79222. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79223. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79224. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79225. }
  79226. }
  79227. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  79228. width *= 0.5;
  79229. height *= 0.5;
  79230. width = Math.max(1.0, width);
  79231. height = Math.max(1.0, height);
  79232. }
  79233. if (currentFace !== undefined) {
  79234. // Loading a single face
  79235. break;
  79236. }
  79237. }
  79238. };
  79239. DDSTools.StoreLODInAlphaChannel = false;
  79240. return DDSTools;
  79241. }());
  79242. BABYLON.DDSTools = DDSTools;
  79243. })(BABYLON || (BABYLON = {}));
  79244. //# sourceMappingURL=babylon.dds.js.map
  79245. "use strict";
  79246. var BABYLON;
  79247. (function (BABYLON) {
  79248. /**
  79249. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  79250. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  79251. */
  79252. var KhronosTextureContainer = /** @class */ (function () {
  79253. /**
  79254. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  79255. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  79256. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  79257. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  79258. */
  79259. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  79260. this.arrayBuffer = arrayBuffer;
  79261. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  79262. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  79263. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  79264. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  79265. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  79266. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  79267. BABYLON.Tools.Error("texture missing KTX identifier");
  79268. return;
  79269. }
  79270. // load the reset of the header in native 32 bit int
  79271. var header = new Int32Array(this.arrayBuffer, 12, 13);
  79272. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  79273. var oppositeEndianess = header[0] === 0x01020304;
  79274. // read all the header elements in order they exist in the file, without modification (sans endainness)
  79275. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  79276. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  79277. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  79278. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  79279. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  79280. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  79281. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  79282. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  79283. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  79284. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  79285. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  79286. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  79287. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  79288. if (this.glType !== 0) {
  79289. BABYLON.Tools.Error("only compressed formats currently supported");
  79290. return;
  79291. }
  79292. else {
  79293. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  79294. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  79295. }
  79296. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  79297. BABYLON.Tools.Error("only 2D textures currently supported");
  79298. return;
  79299. }
  79300. if (this.numberOfArrayElements !== 0) {
  79301. BABYLON.Tools.Error("texture arrays not currently supported");
  79302. return;
  79303. }
  79304. if (this.numberOfFaces !== facesExpected) {
  79305. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  79306. return;
  79307. }
  79308. // we now have a completely validated file, so could use existence of loadType as success
  79309. // would need to make this more elaborate & adjust checks above to support more than one load type
  79310. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  79311. }
  79312. // not as fast hardware based, but will probably never need to use
  79313. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  79314. return ((val & 0xFF) << 24)
  79315. | ((val & 0xFF00) << 8)
  79316. | ((val >> 8) & 0xFF00)
  79317. | ((val >> 24) & 0xFF);
  79318. };
  79319. /**
  79320. * It is assumed that the texture has already been created & is currently bound
  79321. */
  79322. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  79323. switch (this.loadType) {
  79324. case KhronosTextureContainer.COMPRESSED_2D:
  79325. this._upload2DCompressedLevels(gl, loadMipmaps);
  79326. break;
  79327. case KhronosTextureContainer.TEX_2D:
  79328. case KhronosTextureContainer.COMPRESSED_3D:
  79329. case KhronosTextureContainer.TEX_3D:
  79330. }
  79331. };
  79332. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  79333. // initialize width & height for level 1
  79334. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  79335. var width = this.pixelWidth;
  79336. var height = this.pixelHeight;
  79337. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  79338. for (var level = 0; level < mipmapCount; level++) {
  79339. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  79340. for (var face = 0; face < this.numberOfFaces; face++) {
  79341. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  79342. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  79343. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  79344. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  79345. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  79346. }
  79347. width = Math.max(1.0, width * 0.5);
  79348. height = Math.max(1.0, height * 0.5);
  79349. }
  79350. };
  79351. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  79352. // load types
  79353. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  79354. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  79355. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  79356. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  79357. return KhronosTextureContainer;
  79358. }());
  79359. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  79360. })(BABYLON || (BABYLON = {}));
  79361. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  79362. "use strict";
  79363. var BABYLON;
  79364. (function (BABYLON) {
  79365. var Debug = /** @class */ (function () {
  79366. function Debug() {
  79367. }
  79368. Debug.AxesViewer = /** @class */ (function () {
  79369. function AxesViewer(scene, scaleLines) {
  79370. if (scaleLines === void 0) { scaleLines = 1; }
  79371. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79372. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79373. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79374. this.scaleLines = 1;
  79375. this.scaleLines = scaleLines;
  79376. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  79377. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  79378. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  79379. this._xmesh.renderingGroupId = 2;
  79380. this._ymesh.renderingGroupId = 2;
  79381. this._zmesh.renderingGroupId = 2;
  79382. this._xmesh.material.checkReadyOnlyOnce = true;
  79383. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  79384. this._ymesh.material.checkReadyOnlyOnce = true;
  79385. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  79386. this._zmesh.material.checkReadyOnlyOnce = true;
  79387. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  79388. this.scene = scene;
  79389. }
  79390. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  79391. var scaleLines = this.scaleLines;
  79392. if (this._xmesh) {
  79393. this._xmesh.position.copyFrom(position);
  79394. }
  79395. if (this._ymesh) {
  79396. this._ymesh.position.copyFrom(position);
  79397. }
  79398. if (this._zmesh) {
  79399. this._zmesh.position.copyFrom(position);
  79400. }
  79401. var point2 = this._xline[1];
  79402. point2.x = xaxis.x * scaleLines;
  79403. point2.y = xaxis.y * scaleLines;
  79404. point2.z = xaxis.z * scaleLines;
  79405. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  79406. point2 = this._yline[1];
  79407. point2.x = yaxis.x * scaleLines;
  79408. point2.y = yaxis.y * scaleLines;
  79409. point2.z = yaxis.z * scaleLines;
  79410. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  79411. point2 = this._zline[1];
  79412. point2.x = zaxis.x * scaleLines;
  79413. point2.y = zaxis.y * scaleLines;
  79414. point2.z = zaxis.z * scaleLines;
  79415. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  79416. };
  79417. AxesViewer.prototype.dispose = function () {
  79418. if (this._xmesh) {
  79419. this._xmesh.dispose();
  79420. }
  79421. if (this._ymesh) {
  79422. this._ymesh.dispose();
  79423. }
  79424. if (this._zmesh) {
  79425. this._zmesh.dispose();
  79426. }
  79427. this._xmesh = null;
  79428. this._ymesh = null;
  79429. this._zmesh = null;
  79430. this.scene = null;
  79431. };
  79432. return AxesViewer;
  79433. }());
  79434. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  79435. __extends(BoneAxesViewer, _super);
  79436. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  79437. if (scaleLines === void 0) { scaleLines = 1; }
  79438. var _this = _super.call(this, scene, scaleLines) || this;
  79439. _this.pos = BABYLON.Vector3.Zero();
  79440. _this.xaxis = BABYLON.Vector3.Zero();
  79441. _this.yaxis = BABYLON.Vector3.Zero();
  79442. _this.zaxis = BABYLON.Vector3.Zero();
  79443. _this.mesh = mesh;
  79444. _this.bone = bone;
  79445. return _this;
  79446. }
  79447. BoneAxesViewer.prototype.update = function () {
  79448. if (!this.mesh || !this.bone) {
  79449. return;
  79450. }
  79451. var bone = this.bone;
  79452. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  79453. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  79454. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  79455. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  79456. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  79457. };
  79458. BoneAxesViewer.prototype.dispose = function () {
  79459. if (this.mesh) {
  79460. this.mesh = null;
  79461. this.bone = null;
  79462. _super.prototype.dispose.call(this);
  79463. }
  79464. };
  79465. return BoneAxesViewer;
  79466. }(Debug.AxesViewer));
  79467. Debug.PhysicsViewer = /** @class */ (function () {
  79468. function PhysicsViewer(scene) {
  79469. this._impostors = [];
  79470. this._meshes = [];
  79471. this._numMeshes = 0;
  79472. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79473. var physicEngine = this._scene.getPhysicsEngine();
  79474. if (physicEngine) {
  79475. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  79476. }
  79477. }
  79478. PhysicsViewer.prototype._updateDebugMeshes = function () {
  79479. var plugin = this._physicsEnginePlugin;
  79480. for (var i = 0; i < this._numMeshes; i++) {
  79481. var impostor = this._impostors[i];
  79482. if (!impostor) {
  79483. continue;
  79484. }
  79485. if (impostor.isDisposed) {
  79486. this.hideImpostor(this._impostors[i--]);
  79487. }
  79488. else {
  79489. var mesh = this._meshes[i];
  79490. if (mesh && plugin) {
  79491. plugin.syncMeshWithImpostor(mesh, impostor);
  79492. }
  79493. }
  79494. }
  79495. };
  79496. PhysicsViewer.prototype.showImpostor = function (impostor) {
  79497. if (!this._scene) {
  79498. return;
  79499. }
  79500. for (var i = 0; i < this._numMeshes; i++) {
  79501. if (this._impostors[i] == impostor) {
  79502. return;
  79503. }
  79504. }
  79505. var debugMesh = this._getDebugMesh(impostor, this._scene);
  79506. if (debugMesh) {
  79507. this._impostors[this._numMeshes] = impostor;
  79508. this._meshes[this._numMeshes] = debugMesh;
  79509. if (this._numMeshes === 0) {
  79510. this._renderFunction = this._updateDebugMeshes.bind(this);
  79511. this._scene.registerBeforeRender(this._renderFunction);
  79512. }
  79513. this._numMeshes++;
  79514. }
  79515. };
  79516. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  79517. if (!impostor || !this._scene) {
  79518. return;
  79519. }
  79520. var removed = false;
  79521. for (var i = 0; i < this._numMeshes; i++) {
  79522. if (this._impostors[i] == impostor) {
  79523. var mesh = this._meshes[i];
  79524. if (!mesh) {
  79525. continue;
  79526. }
  79527. this._scene.removeMesh(mesh);
  79528. mesh.dispose();
  79529. this._numMeshes--;
  79530. if (this._numMeshes > 0) {
  79531. this._meshes[i] = this._meshes[this._numMeshes];
  79532. this._impostors[i] = this._impostors[this._numMeshes];
  79533. this._meshes[this._numMeshes] = null;
  79534. this._impostors[this._numMeshes] = null;
  79535. }
  79536. else {
  79537. this._meshes[0] = null;
  79538. this._impostors[0] = null;
  79539. }
  79540. removed = true;
  79541. break;
  79542. }
  79543. }
  79544. if (removed && this._numMeshes === 0) {
  79545. this._scene.unregisterBeforeRender(this._renderFunction);
  79546. }
  79547. };
  79548. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  79549. if (!this._debugMaterial) {
  79550. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  79551. this._debugMaterial.wireframe = true;
  79552. }
  79553. return this._debugMaterial;
  79554. };
  79555. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  79556. if (!this._debugBoxMesh) {
  79557. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  79558. this._debugBoxMesh.renderingGroupId = 1;
  79559. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79560. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  79561. scene.removeMesh(this._debugBoxMesh);
  79562. }
  79563. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  79564. };
  79565. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  79566. if (!this._debugSphereMesh) {
  79567. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  79568. this._debugSphereMesh.renderingGroupId = 1;
  79569. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  79570. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  79571. scene.removeMesh(this._debugSphereMesh);
  79572. }
  79573. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  79574. };
  79575. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  79576. var mesh = null;
  79577. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  79578. mesh = this._getDebugBoxMesh(scene);
  79579. impostor.getBoxSizeToRef(mesh.scaling);
  79580. }
  79581. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  79582. mesh = this._getDebugSphereMesh(scene);
  79583. var radius = impostor.getRadius();
  79584. mesh.scaling.x = radius * 2;
  79585. mesh.scaling.y = radius * 2;
  79586. mesh.scaling.z = radius * 2;
  79587. }
  79588. return mesh;
  79589. };
  79590. PhysicsViewer.prototype.dispose = function () {
  79591. for (var i = 0; i < this._numMeshes; i++) {
  79592. this.hideImpostor(this._impostors[i]);
  79593. }
  79594. if (this._debugBoxMesh) {
  79595. this._debugBoxMesh.dispose();
  79596. }
  79597. if (this._debugSphereMesh) {
  79598. this._debugSphereMesh.dispose();
  79599. }
  79600. if (this._debugMaterial) {
  79601. this._debugMaterial.dispose();
  79602. }
  79603. this._impostors.length = 0;
  79604. this._scene = null;
  79605. this._physicsEnginePlugin = null;
  79606. };
  79607. return PhysicsViewer;
  79608. }());
  79609. Debug.SkeletonViewer = /** @class */ (function () {
  79610. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  79611. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  79612. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  79613. this.skeleton = skeleton;
  79614. this.mesh = mesh;
  79615. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  79616. this.renderingGroupId = renderingGroupId;
  79617. this.color = BABYLON.Color3.White();
  79618. this._debugLines = new Array();
  79619. this._isEnabled = false;
  79620. this._scene = scene;
  79621. this.update();
  79622. this._renderFunction = this.update.bind(this);
  79623. }
  79624. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  79625. get: function () {
  79626. return this._isEnabled;
  79627. },
  79628. set: function (value) {
  79629. if (this._isEnabled === value) {
  79630. return;
  79631. }
  79632. this._isEnabled = value;
  79633. if (value) {
  79634. this._scene.registerBeforeRender(this._renderFunction);
  79635. }
  79636. else {
  79637. this._scene.unregisterBeforeRender(this._renderFunction);
  79638. }
  79639. },
  79640. enumerable: true,
  79641. configurable: true
  79642. });
  79643. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  79644. if (x === void 0) { x = 0; }
  79645. if (y === void 0) { y = 0; }
  79646. if (z === void 0) { z = 0; }
  79647. var tmat = BABYLON.Tmp.Matrix[0];
  79648. var parentBone = bone.getParent();
  79649. tmat.copyFrom(bone.getLocalMatrix());
  79650. if (x !== 0 || y !== 0 || z !== 0) {
  79651. var tmat2 = BABYLON.Tmp.Matrix[1];
  79652. BABYLON.Matrix.IdentityToRef(tmat2);
  79653. tmat2.m[12] = x;
  79654. tmat2.m[13] = y;
  79655. tmat2.m[14] = z;
  79656. tmat2.multiplyToRef(tmat, tmat);
  79657. }
  79658. if (parentBone) {
  79659. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  79660. }
  79661. tmat.multiplyToRef(meshMat, tmat);
  79662. position.x = tmat.m[12];
  79663. position.y = tmat.m[13];
  79664. position.z = tmat.m[14];
  79665. };
  79666. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  79667. var len = bones.length;
  79668. var meshPos = this.mesh.position;
  79669. for (var i = 0; i < len; i++) {
  79670. var bone = bones[i];
  79671. var points = this._debugLines[i];
  79672. if (!points) {
  79673. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79674. this._debugLines[i] = points;
  79675. }
  79676. this._getBonePosition(points[0], bone, meshMat);
  79677. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  79678. points[0].subtractInPlace(meshPos);
  79679. points[1].subtractInPlace(meshPos);
  79680. }
  79681. };
  79682. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  79683. var len = bones.length;
  79684. var boneNum = 0;
  79685. var meshPos = this.mesh.position;
  79686. for (var i = len - 1; i >= 0; i--) {
  79687. var childBone = bones[i];
  79688. var parentBone = childBone.getParent();
  79689. if (!parentBone) {
  79690. continue;
  79691. }
  79692. var points = this._debugLines[boneNum];
  79693. if (!points) {
  79694. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79695. this._debugLines[boneNum] = points;
  79696. }
  79697. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  79698. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  79699. points[0].subtractInPlace(meshPos);
  79700. points[1].subtractInPlace(meshPos);
  79701. boneNum++;
  79702. }
  79703. };
  79704. SkeletonViewer.prototype.update = function () {
  79705. if (this.autoUpdateBonesMatrices) {
  79706. this.skeleton.computeAbsoluteTransforms();
  79707. }
  79708. if (this.skeleton.bones[0].length === undefined) {
  79709. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79710. }
  79711. else {
  79712. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  79713. }
  79714. if (!this._debugMesh) {
  79715. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  79716. this._debugMesh.renderingGroupId = this.renderingGroupId;
  79717. }
  79718. else {
  79719. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  79720. }
  79721. this._debugMesh.position.copyFrom(this.mesh.position);
  79722. this._debugMesh.color = this.color;
  79723. };
  79724. SkeletonViewer.prototype.dispose = function () {
  79725. if (this._debugMesh) {
  79726. this.isEnabled = false;
  79727. this._debugMesh.dispose();
  79728. this._debugMesh = null;
  79729. }
  79730. };
  79731. return SkeletonViewer;
  79732. }());
  79733. return Debug;
  79734. }());
  79735. BABYLON.Debug = Debug;
  79736. })(BABYLON || (BABYLON = {}));
  79737. //# sourceMappingURL=babylon.debugModules.js.map
  79738. "use strict";
  79739. var BABYLON;
  79740. (function (BABYLON) {
  79741. var RayHelper = /** @class */ (function () {
  79742. function RayHelper(ray) {
  79743. this.ray = ray;
  79744. }
  79745. RayHelper.CreateAndShow = function (ray, scene, color) {
  79746. var helper = new RayHelper(ray);
  79747. helper.show(scene, color);
  79748. return helper;
  79749. };
  79750. RayHelper.prototype.show = function (scene, color) {
  79751. if (!this._renderFunction && this.ray) {
  79752. var ray = this.ray;
  79753. this._renderFunction = this._render.bind(this);
  79754. this._scene = scene;
  79755. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  79756. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  79757. if (this._renderFunction) {
  79758. this._scene.registerBeforeRender(this._renderFunction);
  79759. }
  79760. }
  79761. if (color && this._renderLine) {
  79762. this._renderLine.color.copyFrom(color);
  79763. }
  79764. };
  79765. RayHelper.prototype.hide = function () {
  79766. if (this._renderFunction && this._scene) {
  79767. this._scene.unregisterBeforeRender(this._renderFunction);
  79768. this._scene = null;
  79769. this._renderFunction = null;
  79770. if (this._renderLine) {
  79771. this._renderLine.dispose();
  79772. this._renderLine = null;
  79773. }
  79774. this._renderPoints = [];
  79775. }
  79776. };
  79777. RayHelper.prototype._render = function () {
  79778. var ray = this.ray;
  79779. if (!ray) {
  79780. return;
  79781. }
  79782. var point = this._renderPoints[1];
  79783. var len = Math.min(ray.length, 1000000);
  79784. point.copyFrom(ray.direction);
  79785. point.scaleInPlace(len);
  79786. point.addInPlace(ray.origin);
  79787. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  79788. };
  79789. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  79790. this._attachedToMesh = mesh;
  79791. var ray = this.ray;
  79792. if (!ray) {
  79793. return;
  79794. }
  79795. if (!ray.direction) {
  79796. ray.direction = BABYLON.Vector3.Zero();
  79797. }
  79798. if (!ray.origin) {
  79799. ray.origin = BABYLON.Vector3.Zero();
  79800. }
  79801. if (length) {
  79802. ray.length = length;
  79803. }
  79804. if (!meshSpaceOrigin) {
  79805. meshSpaceOrigin = BABYLON.Vector3.Zero();
  79806. }
  79807. if (!meshSpaceDirection) {
  79808. // -1 so that this will work with Mesh.lookAt
  79809. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  79810. }
  79811. if (!this._meshSpaceDirection) {
  79812. this._meshSpaceDirection = meshSpaceDirection.clone();
  79813. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  79814. }
  79815. else {
  79816. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  79817. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  79818. }
  79819. if (!this._updateToMeshFunction) {
  79820. this._updateToMeshFunction = this._updateToMesh.bind(this);
  79821. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  79822. }
  79823. this._updateToMesh();
  79824. };
  79825. RayHelper.prototype.detachFromMesh = function () {
  79826. if (this._attachedToMesh) {
  79827. if (this._updateToMeshFunction) {
  79828. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  79829. }
  79830. this._attachedToMesh = null;
  79831. this._updateToMeshFunction = null;
  79832. }
  79833. };
  79834. RayHelper.prototype._updateToMesh = function () {
  79835. var ray = this.ray;
  79836. if (!this._attachedToMesh || !ray) {
  79837. return;
  79838. }
  79839. if (this._attachedToMesh._isDisposed) {
  79840. this.detachFromMesh();
  79841. return;
  79842. }
  79843. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  79844. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  79845. };
  79846. RayHelper.prototype.dispose = function () {
  79847. this.hide();
  79848. this.detachFromMesh();
  79849. this.ray = null;
  79850. };
  79851. return RayHelper;
  79852. }());
  79853. BABYLON.RayHelper = RayHelper;
  79854. })(BABYLON || (BABYLON = {}));
  79855. //# sourceMappingURL=babylon.rayHelper.js.map
  79856. "use strict";
  79857. var BABYLON;
  79858. (function (BABYLON) {
  79859. // load the inspector using require, if not present in the global namespace.
  79860. var DebugLayer = /** @class */ (function () {
  79861. function DebugLayer(scene) {
  79862. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79863. this._scene = scene;
  79864. // load inspector using require, if it doesn't exist on the global namespace.
  79865. }
  79866. /** Creates the inspector window. */
  79867. DebugLayer.prototype._createInspector = function (config) {
  79868. if (config === void 0) { config = {}; }
  79869. var popup = config.popup || false;
  79870. var initialTab = config.initialTab || 0;
  79871. var parentElement = config.parentElement || null;
  79872. if (!this._inspector) {
  79873. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  79874. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  79875. } // else nothing to do,; instance is already existing
  79876. };
  79877. DebugLayer.prototype.isVisible = function () {
  79878. if (!this._inspector) {
  79879. return false;
  79880. }
  79881. return true;
  79882. };
  79883. DebugLayer.prototype.hide = function () {
  79884. if (this._inspector) {
  79885. try {
  79886. this._inspector.dispose();
  79887. }
  79888. catch (e) {
  79889. // If the inspector has been removed directly from the inspector tool
  79890. }
  79891. this._inspector = null;
  79892. }
  79893. };
  79894. DebugLayer.prototype.show = function (config) {
  79895. if (config === void 0) { config = {}; }
  79896. if (typeof this.BJSINSPECTOR == 'undefined') {
  79897. // Load inspector and add it to the DOM
  79898. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  79899. }
  79900. else {
  79901. // Otherwise creates the inspector
  79902. this._createInspector(config);
  79903. }
  79904. };
  79905. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  79906. return DebugLayer;
  79907. }());
  79908. BABYLON.DebugLayer = DebugLayer;
  79909. })(BABYLON || (BABYLON = {}));
  79910. //# sourceMappingURL=babylon.debugLayer.js.map
  79911. "use strict";
  79912. var BABYLON;
  79913. (function (BABYLON) {
  79914. var BoundingBoxRenderer = /** @class */ (function () {
  79915. function BoundingBoxRenderer(scene) {
  79916. this.frontColor = new BABYLON.Color3(1, 1, 1);
  79917. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  79918. this.showBackLines = true;
  79919. this.renderList = new BABYLON.SmartArray(32);
  79920. this._vertexBuffers = {};
  79921. this._scene = scene;
  79922. }
  79923. BoundingBoxRenderer.prototype._prepareRessources = function () {
  79924. if (this._colorShader) {
  79925. return;
  79926. }
  79927. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  79928. attributes: [BABYLON.VertexBuffer.PositionKind],
  79929. uniforms: ["world", "viewProjection", "color"]
  79930. });
  79931. var engine = this._scene.getEngine();
  79932. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  79933. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  79934. this._createIndexBuffer();
  79935. };
  79936. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  79937. var engine = this._scene.getEngine();
  79938. 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]);
  79939. };
  79940. BoundingBoxRenderer.prototype._rebuild = function () {
  79941. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79942. if (vb) {
  79943. vb._rebuild();
  79944. }
  79945. this._createIndexBuffer();
  79946. };
  79947. BoundingBoxRenderer.prototype.reset = function () {
  79948. this.renderList.reset();
  79949. };
  79950. BoundingBoxRenderer.prototype.render = function () {
  79951. if (this.renderList.length === 0) {
  79952. return;
  79953. }
  79954. this._prepareRessources();
  79955. if (!this._colorShader.isReady()) {
  79956. return;
  79957. }
  79958. var engine = this._scene.getEngine();
  79959. engine.setDepthWrite(false);
  79960. this._colorShader._preBind();
  79961. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  79962. var boundingBox = this.renderList.data[boundingBoxIndex];
  79963. var min = boundingBox.minimum;
  79964. var max = boundingBox.maximum;
  79965. var diff = max.subtract(min);
  79966. var median = min.add(diff.scale(0.5));
  79967. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  79968. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  79969. .multiply(boundingBox.getWorldMatrix());
  79970. // VBOs
  79971. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  79972. if (this.showBackLines) {
  79973. // Back
  79974. engine.setDepthFunctionToGreaterOrEqual();
  79975. this._scene.resetCachedMaterial();
  79976. this._colorShader.setColor4("color", this.backColor.toColor4());
  79977. this._colorShader.bind(worldMatrix);
  79978. // Draw order
  79979. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79980. }
  79981. // Front
  79982. engine.setDepthFunctionToLess();
  79983. this._scene.resetCachedMaterial();
  79984. this._colorShader.setColor4("color", this.frontColor.toColor4());
  79985. this._colorShader.bind(worldMatrix);
  79986. // Draw order
  79987. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  79988. }
  79989. this._colorShader.unbind();
  79990. engine.setDepthFunctionToLessOrEqual();
  79991. engine.setDepthWrite(true);
  79992. };
  79993. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  79994. this._prepareRessources();
  79995. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  79996. return;
  79997. }
  79998. var engine = this._scene.getEngine();
  79999. engine.setDepthWrite(false);
  80000. engine.setColorWrite(false);
  80001. this._colorShader._preBind();
  80002. var boundingBox = mesh._boundingInfo.boundingBox;
  80003. var min = boundingBox.minimum;
  80004. var max = boundingBox.maximum;
  80005. var diff = max.subtract(min);
  80006. var median = min.add(diff.scale(0.5));
  80007. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80008. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80009. .multiply(boundingBox.getWorldMatrix());
  80010. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80011. engine.setDepthFunctionToLess();
  80012. this._scene.resetCachedMaterial();
  80013. this._colorShader.bind(worldMatrix);
  80014. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80015. this._colorShader.unbind();
  80016. engine.setDepthFunctionToLessOrEqual();
  80017. engine.setDepthWrite(true);
  80018. engine.setColorWrite(true);
  80019. };
  80020. BoundingBoxRenderer.prototype.dispose = function () {
  80021. if (!this._colorShader) {
  80022. return;
  80023. }
  80024. this.renderList.dispose();
  80025. this._colorShader.dispose();
  80026. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80027. if (buffer) {
  80028. buffer.dispose();
  80029. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80030. }
  80031. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80032. };
  80033. return BoundingBoxRenderer;
  80034. }());
  80035. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  80036. })(BABYLON || (BABYLON = {}));
  80037. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  80038. "use strict";
  80039. var BABYLON;
  80040. (function (BABYLON) {
  80041. var MorphTarget = /** @class */ (function () {
  80042. function MorphTarget(name, influence) {
  80043. if (influence === void 0) { influence = 0; }
  80044. this.name = name;
  80045. this.animations = new Array();
  80046. this._positions = null;
  80047. this._normals = null;
  80048. this._tangents = null;
  80049. this.onInfluenceChanged = new BABYLON.Observable();
  80050. this.influence = influence;
  80051. }
  80052. Object.defineProperty(MorphTarget.prototype, "influence", {
  80053. get: function () {
  80054. return this._influence;
  80055. },
  80056. set: function (influence) {
  80057. if (this._influence === influence) {
  80058. return;
  80059. }
  80060. var previous = this._influence;
  80061. this._influence = influence;
  80062. if (this.onInfluenceChanged.hasObservers) {
  80063. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  80064. }
  80065. },
  80066. enumerable: true,
  80067. configurable: true
  80068. });
  80069. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  80070. get: function () {
  80071. return !!this._positions;
  80072. },
  80073. enumerable: true,
  80074. configurable: true
  80075. });
  80076. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  80077. get: function () {
  80078. return !!this._normals;
  80079. },
  80080. enumerable: true,
  80081. configurable: true
  80082. });
  80083. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  80084. get: function () {
  80085. return !!this._tangents;
  80086. },
  80087. enumerable: true,
  80088. configurable: true
  80089. });
  80090. MorphTarget.prototype.setPositions = function (data) {
  80091. this._positions = data;
  80092. };
  80093. MorphTarget.prototype.getPositions = function () {
  80094. return this._positions;
  80095. };
  80096. MorphTarget.prototype.setNormals = function (data) {
  80097. this._normals = data;
  80098. };
  80099. MorphTarget.prototype.getNormals = function () {
  80100. return this._normals;
  80101. };
  80102. MorphTarget.prototype.setTangents = function (data) {
  80103. this._tangents = data;
  80104. };
  80105. MorphTarget.prototype.getTangents = function () {
  80106. return this._tangents;
  80107. };
  80108. /**
  80109. * Serializes the current target into a Serialization object.
  80110. * Returns the serialized object.
  80111. */
  80112. MorphTarget.prototype.serialize = function () {
  80113. var serializationObject = {};
  80114. serializationObject.name = this.name;
  80115. serializationObject.influence = this.influence;
  80116. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  80117. if (this.hasNormals) {
  80118. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  80119. }
  80120. if (this.hasTangents) {
  80121. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  80122. }
  80123. // Animations
  80124. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  80125. return serializationObject;
  80126. };
  80127. // Statics
  80128. MorphTarget.Parse = function (serializationObject) {
  80129. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  80130. result.setPositions(serializationObject.positions);
  80131. if (serializationObject.normals) {
  80132. result.setNormals(serializationObject.normals);
  80133. }
  80134. if (serializationObject.tangents) {
  80135. result.setTangents(serializationObject.tangents);
  80136. }
  80137. // Animations
  80138. if (serializationObject.animations) {
  80139. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  80140. var parsedAnimation = serializationObject.animations[animationIndex];
  80141. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  80142. }
  80143. }
  80144. return result;
  80145. };
  80146. MorphTarget.FromMesh = function (mesh, name, influence) {
  80147. if (!name) {
  80148. name = mesh.name;
  80149. }
  80150. var result = new MorphTarget(name, influence);
  80151. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80152. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80153. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  80154. }
  80155. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  80156. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  80157. }
  80158. return result;
  80159. };
  80160. return MorphTarget;
  80161. }());
  80162. BABYLON.MorphTarget = MorphTarget;
  80163. })(BABYLON || (BABYLON = {}));
  80164. //# sourceMappingURL=babylon.morphTarget.js.map
  80165. "use strict";
  80166. var BABYLON;
  80167. (function (BABYLON) {
  80168. var MorphTargetManager = /** @class */ (function () {
  80169. function MorphTargetManager(scene) {
  80170. if (scene === void 0) { scene = null; }
  80171. this._targets = new Array();
  80172. this._targetObservable = new Array();
  80173. this._activeTargets = new BABYLON.SmartArray(16);
  80174. this._supportsNormals = false;
  80175. this._supportsTangents = false;
  80176. this._vertexCount = 0;
  80177. this._uniqueId = 0;
  80178. this._tempInfluences = new Array();
  80179. if (!scene) {
  80180. scene = BABYLON.Engine.LastCreatedScene;
  80181. }
  80182. this._scene = scene;
  80183. if (this._scene) {
  80184. this._scene.morphTargetManagers.push(this);
  80185. this._uniqueId = this._scene.getUniqueId();
  80186. }
  80187. }
  80188. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80189. get: function () {
  80190. return this._uniqueId;
  80191. },
  80192. enumerable: true,
  80193. configurable: true
  80194. });
  80195. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80196. get: function () {
  80197. return this._vertexCount;
  80198. },
  80199. enumerable: true,
  80200. configurable: true
  80201. });
  80202. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80203. get: function () {
  80204. return this._supportsNormals;
  80205. },
  80206. enumerable: true,
  80207. configurable: true
  80208. });
  80209. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80210. get: function () {
  80211. return this._supportsTangents;
  80212. },
  80213. enumerable: true,
  80214. configurable: true
  80215. });
  80216. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80217. get: function () {
  80218. return this._targets.length;
  80219. },
  80220. enumerable: true,
  80221. configurable: true
  80222. });
  80223. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80224. get: function () {
  80225. return this._activeTargets.length;
  80226. },
  80227. enumerable: true,
  80228. configurable: true
  80229. });
  80230. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  80231. get: function () {
  80232. return this._influences;
  80233. },
  80234. enumerable: true,
  80235. configurable: true
  80236. });
  80237. MorphTargetManager.prototype.getActiveTarget = function (index) {
  80238. return this._activeTargets.data[index];
  80239. };
  80240. MorphTargetManager.prototype.getTarget = function (index) {
  80241. return this._targets[index];
  80242. };
  80243. MorphTargetManager.prototype.addTarget = function (target) {
  80244. var _this = this;
  80245. this._targets.push(target);
  80246. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  80247. _this._syncActiveTargets(needUpdate);
  80248. }));
  80249. this._syncActiveTargets(true);
  80250. };
  80251. MorphTargetManager.prototype.removeTarget = function (target) {
  80252. var index = this._targets.indexOf(target);
  80253. if (index >= 0) {
  80254. this._targets.splice(index, 1);
  80255. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  80256. this._syncActiveTargets(true);
  80257. }
  80258. };
  80259. /**
  80260. * Serializes the current manager into a Serialization object.
  80261. * Returns the serialized object.
  80262. */
  80263. MorphTargetManager.prototype.serialize = function () {
  80264. var serializationObject = {};
  80265. serializationObject.id = this.uniqueId;
  80266. serializationObject.targets = [];
  80267. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80268. var target = _a[_i];
  80269. serializationObject.targets.push(target.serialize());
  80270. }
  80271. return serializationObject;
  80272. };
  80273. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  80274. var influenceCount = 0;
  80275. this._activeTargets.reset();
  80276. this._supportsNormals = true;
  80277. this._supportsTangents = true;
  80278. this._vertexCount = 0;
  80279. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80280. var target = _a[_i];
  80281. this._activeTargets.push(target);
  80282. this._tempInfluences[influenceCount++] = target.influence;
  80283. var positions = target.getPositions();
  80284. if (positions) {
  80285. this._supportsNormals = this._supportsNormals && target.hasNormals;
  80286. this._supportsTangents = this._supportsTangents && target.hasTangents;
  80287. var vertexCount = positions.length / 3;
  80288. if (this._vertexCount === 0) {
  80289. this._vertexCount = vertexCount;
  80290. }
  80291. else if (this._vertexCount !== vertexCount) {
  80292. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  80293. return;
  80294. }
  80295. }
  80296. }
  80297. if (!this._influences || this._influences.length !== influenceCount) {
  80298. this._influences = new Float32Array(influenceCount);
  80299. }
  80300. for (var index = 0; index < influenceCount; index++) {
  80301. this._influences[index] = this._tempInfluences[index];
  80302. }
  80303. if (needUpdate && this._scene) {
  80304. // Flag meshes as dirty to resync with the active targets
  80305. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  80306. var mesh = _c[_b];
  80307. if (mesh.morphTargetManager === this) {
  80308. mesh._syncGeometryWithMorphTargetManager();
  80309. }
  80310. }
  80311. }
  80312. };
  80313. // Statics
  80314. MorphTargetManager.Parse = function (serializationObject, scene) {
  80315. var result = new MorphTargetManager(scene);
  80316. result._uniqueId = serializationObject.id;
  80317. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  80318. var targetData = _a[_i];
  80319. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  80320. }
  80321. return result;
  80322. };
  80323. return MorphTargetManager;
  80324. }());
  80325. BABYLON.MorphTargetManager = MorphTargetManager;
  80326. })(BABYLON || (BABYLON = {}));
  80327. //# sourceMappingURL=babylon.morphTargetManager.js.map
  80328. "use strict";
  80329. var BABYLON;
  80330. (function (BABYLON) {
  80331. var Octree = /** @class */ (function () {
  80332. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  80333. if (maxDepth === void 0) { maxDepth = 2; }
  80334. this.maxDepth = maxDepth;
  80335. this.dynamicContent = new Array();
  80336. this._maxBlockCapacity = maxBlockCapacity || 64;
  80337. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  80338. this._creationFunc = creationFunc;
  80339. }
  80340. // Methods
  80341. Octree.prototype.update = function (worldMin, worldMax, entries) {
  80342. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  80343. };
  80344. Octree.prototype.addMesh = function (entry) {
  80345. for (var index = 0; index < this.blocks.length; index++) {
  80346. var block = this.blocks[index];
  80347. block.addEntry(entry);
  80348. }
  80349. };
  80350. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  80351. this._selectionContent.reset();
  80352. for (var index = 0; index < this.blocks.length; index++) {
  80353. var block = this.blocks[index];
  80354. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  80355. }
  80356. if (allowDuplicate) {
  80357. this._selectionContent.concat(this.dynamicContent);
  80358. }
  80359. else {
  80360. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80361. }
  80362. return this._selectionContent;
  80363. };
  80364. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  80365. this._selectionContent.reset();
  80366. for (var index = 0; index < this.blocks.length; index++) {
  80367. var block = this.blocks[index];
  80368. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  80369. }
  80370. if (allowDuplicate) {
  80371. this._selectionContent.concat(this.dynamicContent);
  80372. }
  80373. else {
  80374. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80375. }
  80376. return this._selectionContent;
  80377. };
  80378. Octree.prototype.intersectsRay = function (ray) {
  80379. this._selectionContent.reset();
  80380. for (var index = 0; index < this.blocks.length; index++) {
  80381. var block = this.blocks[index];
  80382. block.intersectsRay(ray, this._selectionContent);
  80383. }
  80384. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  80385. return this._selectionContent;
  80386. };
  80387. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  80388. target.blocks = new Array();
  80389. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  80390. // Segmenting space
  80391. for (var x = 0; x < 2; x++) {
  80392. for (var y = 0; y < 2; y++) {
  80393. for (var z = 0; z < 2; z++) {
  80394. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  80395. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  80396. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  80397. block.addEntries(entries);
  80398. target.blocks.push(block);
  80399. }
  80400. }
  80401. }
  80402. };
  80403. Octree.CreationFuncForMeshes = function (entry, block) {
  80404. var boundingInfo = entry.getBoundingInfo();
  80405. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80406. block.entries.push(entry);
  80407. }
  80408. };
  80409. Octree.CreationFuncForSubMeshes = function (entry, block) {
  80410. var boundingInfo = entry.getBoundingInfo();
  80411. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  80412. block.entries.push(entry);
  80413. }
  80414. };
  80415. return Octree;
  80416. }());
  80417. BABYLON.Octree = Octree;
  80418. })(BABYLON || (BABYLON = {}));
  80419. //# sourceMappingURL=babylon.octree.js.map
  80420. "use strict";
  80421. var BABYLON;
  80422. (function (BABYLON) {
  80423. var OctreeBlock = /** @class */ (function () {
  80424. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  80425. this.entries = new Array();
  80426. this._boundingVectors = new Array();
  80427. this._capacity = capacity;
  80428. this._depth = depth;
  80429. this._maxDepth = maxDepth;
  80430. this._creationFunc = creationFunc;
  80431. this._minPoint = minPoint;
  80432. this._maxPoint = maxPoint;
  80433. this._boundingVectors.push(minPoint.clone());
  80434. this._boundingVectors.push(maxPoint.clone());
  80435. this._boundingVectors.push(minPoint.clone());
  80436. this._boundingVectors[2].x = maxPoint.x;
  80437. this._boundingVectors.push(minPoint.clone());
  80438. this._boundingVectors[3].y = maxPoint.y;
  80439. this._boundingVectors.push(minPoint.clone());
  80440. this._boundingVectors[4].z = maxPoint.z;
  80441. this._boundingVectors.push(maxPoint.clone());
  80442. this._boundingVectors[5].z = minPoint.z;
  80443. this._boundingVectors.push(maxPoint.clone());
  80444. this._boundingVectors[6].x = minPoint.x;
  80445. this._boundingVectors.push(maxPoint.clone());
  80446. this._boundingVectors[7].y = minPoint.y;
  80447. }
  80448. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  80449. // Property
  80450. get: function () {
  80451. return this._capacity;
  80452. },
  80453. enumerable: true,
  80454. configurable: true
  80455. });
  80456. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  80457. get: function () {
  80458. return this._minPoint;
  80459. },
  80460. enumerable: true,
  80461. configurable: true
  80462. });
  80463. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  80464. get: function () {
  80465. return this._maxPoint;
  80466. },
  80467. enumerable: true,
  80468. configurable: true
  80469. });
  80470. // Methods
  80471. OctreeBlock.prototype.addEntry = function (entry) {
  80472. if (this.blocks) {
  80473. for (var index = 0; index < this.blocks.length; index++) {
  80474. var block = this.blocks[index];
  80475. block.addEntry(entry);
  80476. }
  80477. return;
  80478. }
  80479. this._creationFunc(entry, this);
  80480. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  80481. this.createInnerBlocks();
  80482. }
  80483. };
  80484. OctreeBlock.prototype.addEntries = function (entries) {
  80485. for (var index = 0; index < entries.length; index++) {
  80486. var mesh = entries[index];
  80487. this.addEntry(mesh);
  80488. }
  80489. };
  80490. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  80491. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  80492. if (this.blocks) {
  80493. for (var index = 0; index < this.blocks.length; index++) {
  80494. var block = this.blocks[index];
  80495. block.select(frustumPlanes, selection, allowDuplicate);
  80496. }
  80497. return;
  80498. }
  80499. if (allowDuplicate) {
  80500. selection.concat(this.entries);
  80501. }
  80502. else {
  80503. selection.concatWithNoDuplicate(this.entries);
  80504. }
  80505. }
  80506. };
  80507. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  80508. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  80509. if (this.blocks) {
  80510. for (var index = 0; index < this.blocks.length; index++) {
  80511. var block = this.blocks[index];
  80512. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  80513. }
  80514. return;
  80515. }
  80516. if (allowDuplicate) {
  80517. selection.concat(this.entries);
  80518. }
  80519. else {
  80520. selection.concatWithNoDuplicate(this.entries);
  80521. }
  80522. }
  80523. };
  80524. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  80525. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  80526. if (this.blocks) {
  80527. for (var index = 0; index < this.blocks.length; index++) {
  80528. var block = this.blocks[index];
  80529. block.intersectsRay(ray, selection);
  80530. }
  80531. return;
  80532. }
  80533. selection.concatWithNoDuplicate(this.entries);
  80534. }
  80535. };
  80536. OctreeBlock.prototype.createInnerBlocks = function () {
  80537. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  80538. };
  80539. return OctreeBlock;
  80540. }());
  80541. BABYLON.OctreeBlock = OctreeBlock;
  80542. })(BABYLON || (BABYLON = {}));
  80543. //# sourceMappingURL=babylon.octreeBlock.js.map
  80544. "use strict";
  80545. var BABYLON;
  80546. (function (BABYLON) {
  80547. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  80548. __extends(VRDistortionCorrectionPostProcess, _super);
  80549. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  80550. var _this = _super.call(this, name, "vrDistortionCorrection", [
  80551. 'LensCenter',
  80552. 'Scale',
  80553. 'ScaleIn',
  80554. 'HmdWarpParam'
  80555. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  80556. _this._isRightEye = isRightEye;
  80557. _this._distortionFactors = vrMetrics.distortionK;
  80558. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  80559. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  80560. _this.adaptScaleToCurrentViewport = true;
  80561. _this.onSizeChangedObservable.add(function () {
  80562. _this.aspectRatio = _this.width * .5 / _this.height;
  80563. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  80564. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  80565. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  80566. });
  80567. _this.onApplyObservable.add(function (effect) {
  80568. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  80569. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  80570. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  80571. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  80572. });
  80573. return _this;
  80574. }
  80575. return VRDistortionCorrectionPostProcess;
  80576. }(BABYLON.PostProcess));
  80577. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  80578. })(BABYLON || (BABYLON = {}));
  80579. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  80580. "use strict";
  80581. var BABYLON;
  80582. (function (BABYLON) {
  80583. var AnaglyphPostProcess = /** @class */ (function (_super) {
  80584. __extends(AnaglyphPostProcess, _super);
  80585. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  80586. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  80587. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80588. _this.onApplyObservable.add(function (effect) {
  80589. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  80590. });
  80591. return _this;
  80592. }
  80593. return AnaglyphPostProcess;
  80594. }(BABYLON.PostProcess));
  80595. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  80596. })(BABYLON || (BABYLON = {}));
  80597. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  80598. "use strict";
  80599. var BABYLON;
  80600. (function (BABYLON) {
  80601. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  80602. __extends(StereoscopicInterlacePostProcess, _super);
  80603. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  80604. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  80605. _this._passedProcess = rigCameras[0]._rigPostProcess;
  80606. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80607. _this.onSizeChangedObservable.add(function () {
  80608. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  80609. });
  80610. _this.onApplyObservable.add(function (effect) {
  80611. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  80612. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  80613. });
  80614. return _this;
  80615. }
  80616. return StereoscopicInterlacePostProcess;
  80617. }(BABYLON.PostProcess));
  80618. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  80619. })(BABYLON || (BABYLON = {}));
  80620. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  80621. "use strict";
  80622. var BABYLON;
  80623. (function (BABYLON) {
  80624. /**
  80625. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  80626. * Screen rotation is taken into account.
  80627. */
  80628. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  80629. function FreeCameraDeviceOrientationInput() {
  80630. var _this = this;
  80631. this._screenOrientationAngle = 0;
  80632. this._screenQuaternion = new BABYLON.Quaternion();
  80633. this._alpha = 0;
  80634. this._beta = 0;
  80635. this._gamma = 0;
  80636. this._orientationChanged = function () {
  80637. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  80638. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  80639. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  80640. };
  80641. this._deviceOrientation = function (evt) {
  80642. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  80643. _this._beta = evt.beta !== null ? evt.beta : 0;
  80644. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  80645. };
  80646. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  80647. this._orientationChanged();
  80648. }
  80649. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  80650. get: function () {
  80651. return this._camera;
  80652. },
  80653. set: function (camera) {
  80654. this._camera = camera;
  80655. if (this._camera != null && !this._camera.rotationQuaternion) {
  80656. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  80657. }
  80658. },
  80659. enumerable: true,
  80660. configurable: true
  80661. });
  80662. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80663. window.addEventListener("orientationchange", this._orientationChanged);
  80664. window.addEventListener("deviceorientation", this._deviceOrientation);
  80665. //In certain cases, the attach control is called AFTER orientation was changed,
  80666. //So this is needed.
  80667. this._orientationChanged();
  80668. };
  80669. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  80670. window.removeEventListener("orientationchange", this._orientationChanged);
  80671. window.removeEventListener("deviceorientation", this._deviceOrientation);
  80672. };
  80673. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  80674. //if no device orientation provided, don't update the rotation.
  80675. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  80676. if (!this._alpha)
  80677. return;
  80678. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  80679. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  80680. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  80681. //Mirror on XY Plane
  80682. this._camera.rotationQuaternion.z *= -1;
  80683. this._camera.rotationQuaternion.w *= -1;
  80684. };
  80685. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  80686. return "FreeCameraDeviceOrientationInput";
  80687. };
  80688. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  80689. return "deviceOrientation";
  80690. };
  80691. return FreeCameraDeviceOrientationInput;
  80692. }());
  80693. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  80694. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  80695. })(BABYLON || (BABYLON = {}));
  80696. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  80697. "use strict";
  80698. var BABYLON;
  80699. (function (BABYLON) {
  80700. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  80701. function ArcRotateCameraVRDeviceOrientationInput() {
  80702. this.alphaCorrection = 1;
  80703. this.betaCorrection = 1;
  80704. this.gammaCorrection = 1;
  80705. this._alpha = 0;
  80706. this._gamma = 0;
  80707. this._dirty = false;
  80708. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  80709. }
  80710. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  80711. this.camera.attachControl(element, noPreventDefault);
  80712. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  80713. };
  80714. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  80715. if (evt.alpha !== null) {
  80716. this._alpha = +evt.alpha | 0;
  80717. }
  80718. if (evt.gamma !== null) {
  80719. this._gamma = +evt.gamma | 0;
  80720. }
  80721. this._dirty = true;
  80722. };
  80723. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  80724. if (this._dirty) {
  80725. this._dirty = false;
  80726. if (this._gamma < 0) {
  80727. this._gamma = 180 + this._gamma;
  80728. }
  80729. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  80730. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  80731. }
  80732. };
  80733. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  80734. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  80735. };
  80736. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  80737. return "ArcRotateCameraVRDeviceOrientationInput";
  80738. };
  80739. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  80740. return "VRDeviceOrientation";
  80741. };
  80742. return ArcRotateCameraVRDeviceOrientationInput;
  80743. }());
  80744. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  80745. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  80746. })(BABYLON || (BABYLON = {}));
  80747. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  80748. "use strict";
  80749. var BABYLON;
  80750. (function (BABYLON) {
  80751. var VRCameraMetrics = /** @class */ (function () {
  80752. function VRCameraMetrics() {
  80753. this.compensateDistortion = true;
  80754. }
  80755. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  80756. get: function () {
  80757. return this.hResolution / (2 * this.vResolution);
  80758. },
  80759. enumerable: true,
  80760. configurable: true
  80761. });
  80762. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  80763. get: function () {
  80764. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  80765. },
  80766. enumerable: true,
  80767. configurable: true
  80768. });
  80769. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  80770. get: function () {
  80771. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80772. var h = (4 * meters) / this.hScreenSize;
  80773. return BABYLON.Matrix.Translation(h, 0, 0);
  80774. },
  80775. enumerable: true,
  80776. configurable: true
  80777. });
  80778. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  80779. get: function () {
  80780. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  80781. var h = (4 * meters) / this.hScreenSize;
  80782. return BABYLON.Matrix.Translation(-h, 0, 0);
  80783. },
  80784. enumerable: true,
  80785. configurable: true
  80786. });
  80787. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  80788. get: function () {
  80789. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  80790. },
  80791. enumerable: true,
  80792. configurable: true
  80793. });
  80794. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  80795. get: function () {
  80796. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  80797. },
  80798. enumerable: true,
  80799. configurable: true
  80800. });
  80801. VRCameraMetrics.GetDefault = function () {
  80802. var result = new VRCameraMetrics();
  80803. result.hResolution = 1280;
  80804. result.vResolution = 800;
  80805. result.hScreenSize = 0.149759993;
  80806. result.vScreenSize = 0.0935999975;
  80807. result.vScreenCenter = 0.0467999987;
  80808. result.eyeToScreenDistance = 0.0410000011;
  80809. result.lensSeparationDistance = 0.0635000020;
  80810. result.interpupillaryDistance = 0.0640000030;
  80811. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  80812. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  80813. result.postProcessScaleFactor = 1.714605507808412;
  80814. result.lensCenterOffset = 0.151976421;
  80815. return result;
  80816. };
  80817. return VRCameraMetrics;
  80818. }());
  80819. BABYLON.VRCameraMetrics = VRCameraMetrics;
  80820. })(BABYLON || (BABYLON = {}));
  80821. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  80822. "use strict";
  80823. var BABYLON;
  80824. (function (BABYLON) {
  80825. /**
  80826. * This represents a WebVR camera.
  80827. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  80828. * @example http://doc.babylonjs.com/how_to/webvr_camera
  80829. */
  80830. var WebVRFreeCamera = /** @class */ (function (_super) {
  80831. __extends(WebVRFreeCamera, _super);
  80832. /**
  80833. * Instantiates a WebVRFreeCamera.
  80834. * @param name The name of the WebVRFreeCamera
  80835. * @param position The starting anchor position for the camera
  80836. * @param scene The scene the camera belongs to
  80837. * @param webVROptions a set of customizable options for the webVRCamera
  80838. */
  80839. function WebVRFreeCamera(name, position, scene, webVROptions) {
  80840. if (webVROptions === void 0) { webVROptions = {}; }
  80841. var _this = _super.call(this, name, position, scene) || this;
  80842. _this.webVROptions = webVROptions;
  80843. /**
  80844. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  80845. */
  80846. _this._vrDevice = null;
  80847. /**
  80848. * The rawPose of the vrDevice.
  80849. */
  80850. _this.rawPose = null;
  80851. _this._specsVersion = "1.1";
  80852. _this._attached = false;
  80853. _this._descendants = [];
  80854. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80855. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80856. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  80857. _this._standingMatrix = null;
  80858. /**
  80859. * Represents device position in babylon space.
  80860. */
  80861. _this.devicePosition = BABYLON.Vector3.Zero();
  80862. /**
  80863. * Represents device rotation in babylon space.
  80864. */
  80865. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  80866. /**
  80867. * The scale of the device to be used when translating from device space to babylon space.
  80868. */
  80869. _this.deviceScaleFactor = 1;
  80870. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80871. _this._worldToDevice = BABYLON.Matrix.Identity();
  80872. /**
  80873. * References to the webVR controllers for the vrDevice.
  80874. */
  80875. _this.controllers = [];
  80876. /**
  80877. * Emits an event when a controller is attached.
  80878. */
  80879. _this.onControllersAttachedObservable = new BABYLON.Observable();
  80880. /**
  80881. * Emits an event when a controller's mesh has been loaded;
  80882. */
  80883. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  80884. /**
  80885. * If the rig cameras be used as parent instead of this camera.
  80886. */
  80887. _this.rigParenting = true;
  80888. _this._defaultHeight = undefined;
  80889. _this._workingVector = BABYLON.Vector3.Zero();
  80890. _this._oneVector = BABYLON.Vector3.One();
  80891. _this._workingMatrix = BABYLON.Matrix.Identity();
  80892. _this._cache.position = BABYLON.Vector3.Zero();
  80893. if (webVROptions.defaultHeight) {
  80894. _this._defaultHeight = webVROptions.defaultHeight;
  80895. _this.position.y = _this._defaultHeight;
  80896. }
  80897. _this.minZ = 0.1;
  80898. //legacy support - the compensation boolean was removed.
  80899. if (arguments.length === 5) {
  80900. _this.webVROptions = arguments[4];
  80901. }
  80902. // default webVR options
  80903. if (_this.webVROptions.trackPosition == undefined) {
  80904. _this.webVROptions.trackPosition = true;
  80905. }
  80906. if (_this.webVROptions.controllerMeshes == undefined) {
  80907. _this.webVROptions.controllerMeshes = true;
  80908. }
  80909. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  80910. _this.webVROptions.defaultLightingOnControllers = true;
  80911. }
  80912. _this.rotationQuaternion = new BABYLON.Quaternion();
  80913. if (_this.webVROptions && _this.webVROptions.positionScale) {
  80914. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  80915. }
  80916. //enable VR
  80917. var engine = _this.getEngine();
  80918. _this._onVREnabled = function (success) { if (success) {
  80919. _this.initControllers();
  80920. } };
  80921. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  80922. engine.initWebVR().add(function (event) {
  80923. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  80924. return;
  80925. }
  80926. _this._vrDevice = event.vrDisplay;
  80927. //reset the rig parameters.
  80928. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  80929. if (_this._attached) {
  80930. _this.getEngine().enableVR();
  80931. }
  80932. });
  80933. if (typeof (VRFrameData) !== "undefined")
  80934. _this._frameData = new VRFrameData();
  80935. /**
  80936. * The idea behind the following lines:
  80937. * objects that have the camera as parent should actually have the rig cameras as a parent.
  80938. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  80939. * the second will not show it correctly.
  80940. *
  80941. * To solve this - each object that has the camera as parent will be added to a protected array.
  80942. * When the rig camera renders, it will take this array and set all of those to be its children.
  80943. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  80944. * Amazing!
  80945. */
  80946. scene.onBeforeCameraRenderObservable.add(function (camera) {
  80947. if (camera.parent === _this && _this.rigParenting) {
  80948. _this._descendants = _this.getDescendants(true, function (n) {
  80949. // don't take the cameras or the controllers!
  80950. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  80951. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  80952. return !isController && !isRigCamera;
  80953. });
  80954. _this._descendants.forEach(function (node) {
  80955. node.parent = camera;
  80956. });
  80957. }
  80958. });
  80959. scene.onAfterCameraRenderObservable.add(function (camera) {
  80960. if (camera.parent === _this && _this.rigParenting) {
  80961. _this._descendants.forEach(function (node) {
  80962. node.parent = _this;
  80963. });
  80964. }
  80965. });
  80966. return _this;
  80967. }
  80968. /**
  80969. * Gets the device distance from the ground in meters.
  80970. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  80971. */
  80972. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  80973. if (this._standingMatrix) {
  80974. // Add standing matrix offset to get real offset from ground in room
  80975. this._standingMatrix.getTranslationToRef(this._workingVector);
  80976. return this._deviceRoomPosition.y + this._workingVector.y;
  80977. }
  80978. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  80979. return this._defaultHeight || 0;
  80980. };
  80981. /**
  80982. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  80983. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  80984. */
  80985. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  80986. var _this = this;
  80987. if (callback === void 0) { callback = function (bool) { }; }
  80988. // Use standing matrix if available
  80989. this.getEngine().initWebVRAsync().then(function (result) {
  80990. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  80991. callback(false);
  80992. }
  80993. else {
  80994. _this._standingMatrix = new BABYLON.Matrix();
  80995. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  80996. if (!_this.getScene().useRightHandedSystem) {
  80997. [2, 6, 8, 9, 14].forEach(function (num) {
  80998. if (_this._standingMatrix) {
  80999. _this._standingMatrix.m[num] *= -1;
  81000. }
  81001. });
  81002. }
  81003. callback(true);
  81004. }
  81005. });
  81006. };
  81007. /**
  81008. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81009. * @returns A promise with a boolean set to if the standing matrix is supported.
  81010. */
  81011. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  81012. var _this = this;
  81013. return new Promise(function (res, rej) {
  81014. _this.useStandingMatrix(function (supported) {
  81015. res(supported);
  81016. });
  81017. });
  81018. };
  81019. /**
  81020. * Disposes the camera
  81021. */
  81022. WebVRFreeCamera.prototype.dispose = function () {
  81023. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  81024. _super.prototype.dispose.call(this);
  81025. };
  81026. /**
  81027. * Gets a vrController by name.
  81028. * @param name The name of the controller to retreive
  81029. * @returns the controller matching the name specified or null if not found
  81030. */
  81031. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  81032. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  81033. var gp = _a[_i];
  81034. if (gp.hand === name) {
  81035. return gp;
  81036. }
  81037. }
  81038. return null;
  81039. };
  81040. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  81041. /**
  81042. * The controller corrisponding to the users left hand.
  81043. */
  81044. get: function () {
  81045. if (!this._leftController) {
  81046. this._leftController = this.getControllerByName("left");
  81047. }
  81048. return this._leftController;
  81049. },
  81050. enumerable: true,
  81051. configurable: true
  81052. });
  81053. ;
  81054. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  81055. /**
  81056. * The controller corrisponding to the users right hand.
  81057. */
  81058. get: function () {
  81059. if (!this._rightController) {
  81060. this._rightController = this.getControllerByName("right");
  81061. }
  81062. return this._rightController;
  81063. },
  81064. enumerable: true,
  81065. configurable: true
  81066. });
  81067. ;
  81068. /**
  81069. * Casts a ray forward from the vrCamera's gaze.
  81070. * @param length Length of the ray (default: 100)
  81071. * @returns the ray corrisponding to the gaze
  81072. */
  81073. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  81074. if (length === void 0) { length = 100; }
  81075. if (this.leftCamera) {
  81076. // Use left eye to avoid computation to compute center on every call
  81077. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  81078. }
  81079. else {
  81080. return _super.prototype.getForwardRay.call(this, length);
  81081. }
  81082. };
  81083. /**
  81084. * Updates the camera based on device's frame data
  81085. */
  81086. WebVRFreeCamera.prototype._checkInputs = function () {
  81087. if (this._vrDevice && this._vrDevice.isPresenting) {
  81088. this._vrDevice.getFrameData(this._frameData);
  81089. this.updateFromDevice(this._frameData.pose);
  81090. }
  81091. _super.prototype._checkInputs.call(this);
  81092. };
  81093. /**
  81094. * Updates the poseControlled values based on the input device pose.
  81095. * @param poseData Pose coming from the device
  81096. */
  81097. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  81098. if (poseData && poseData.orientation) {
  81099. this.rawPose = poseData;
  81100. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  81101. if (this.getScene().useRightHandedSystem) {
  81102. this._deviceRoomRotationQuaternion.z *= -1;
  81103. this._deviceRoomRotationQuaternion.w *= -1;
  81104. }
  81105. if (this.webVROptions.trackPosition && this.rawPose.position) {
  81106. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  81107. if (this.getScene().useRightHandedSystem) {
  81108. this._deviceRoomPosition.z *= -1;
  81109. }
  81110. }
  81111. }
  81112. };
  81113. /**
  81114. * WebVR's attach control will start broadcasting frames to the device.
  81115. * Note that in certain browsers (chrome for example) this function must be called
  81116. * within a user-interaction callback. Example:
  81117. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  81118. *
  81119. * @param element html element to attach the vrDevice to
  81120. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  81121. */
  81122. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  81123. _super.prototype.attachControl.call(this, element, noPreventDefault);
  81124. this._attached = true;
  81125. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  81126. if (this._vrDevice) {
  81127. this.getEngine().enableVR();
  81128. }
  81129. };
  81130. /**
  81131. * Detaches the camera from the html element and disables VR
  81132. *
  81133. * @param element html element to detach from
  81134. */
  81135. WebVRFreeCamera.prototype.detachControl = function (element) {
  81136. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81137. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81138. _super.prototype.detachControl.call(this, element);
  81139. this._attached = false;
  81140. this.getEngine().disableVR();
  81141. };
  81142. /**
  81143. * @returns the name of this class
  81144. */
  81145. WebVRFreeCamera.prototype.getClassName = function () {
  81146. return "WebVRFreeCamera";
  81147. };
  81148. /**
  81149. * Calls resetPose on the vrDisplay
  81150. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  81151. */
  81152. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  81153. //uses the vrDisplay's "resetPose()".
  81154. //pitch and roll won't be affected.
  81155. this._vrDevice.resetPose();
  81156. };
  81157. /**
  81158. * Updates the rig cameras (left and right eye)
  81159. */
  81160. WebVRFreeCamera.prototype._updateRigCameras = function () {
  81161. var camLeft = this._rigCameras[0];
  81162. var camRight = this._rigCameras[1];
  81163. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81164. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81165. camLeft.position.copyFrom(this._deviceRoomPosition);
  81166. camRight.position.copyFrom(this._deviceRoomPosition);
  81167. };
  81168. /**
  81169. * Updates the cached values of the camera
  81170. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  81171. */
  81172. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81173. var _this = this;
  81174. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81175. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81176. if (!this.updateCacheCalled) {
  81177. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81178. this.updateCacheCalled = true;
  81179. this.update();
  81180. }
  81181. // Set working vector to the device position in room space rotated by the new rotation
  81182. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81183. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81184. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81185. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81186. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81187. // Add translation from anchor position
  81188. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81189. this._workingVector.addInPlace(this.position);
  81190. this._workingVector.subtractInPlace(this._cache.position);
  81191. this._deviceToWorld.setTranslation(this._workingVector);
  81192. // Set an inverted matrix to be used when updating the camera
  81193. this._deviceToWorld.invertToRef(this._worldToDevice);
  81194. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81195. this.controllers.forEach(function (controller) {
  81196. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81197. controller.update();
  81198. });
  81199. }
  81200. if (!ignoreParentClass) {
  81201. _super.prototype._updateCache.call(this);
  81202. }
  81203. this.updateCacheCalled = false;
  81204. };
  81205. /**
  81206. * Updates the current device position and rotation in the babylon world
  81207. */
  81208. WebVRFreeCamera.prototype.update = function () {
  81209. // Get current device position in babylon world
  81210. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81211. // Get current device rotation in babylon world
  81212. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81213. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81214. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81215. _super.prototype.update.call(this);
  81216. };
  81217. /**
  81218. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  81219. * @returns an identity matrix
  81220. */
  81221. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81222. return BABYLON.Matrix.Identity();
  81223. };
  81224. /**
  81225. * This function is called by the two RIG cameras.
  81226. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81227. */
  81228. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  81229. var _this = this;
  81230. // Update the parent camera prior to using a child camera to avoid desynchronization
  81231. var parentCamera = this._cameraRigParams["parentCamera"];
  81232. parentCamera._updateCache();
  81233. //WebVR 1.1
  81234. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  81235. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  81236. if (!this.getScene().useRightHandedSystem) {
  81237. [2, 6, 8, 9, 14].forEach(function (num) {
  81238. _this._webvrViewMatrix.m[num] *= -1;
  81239. });
  81240. }
  81241. // update the camera rotation matrix
  81242. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  81243. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  81244. // Computing target and final matrix
  81245. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  81246. // should the view matrix be updated with scale and position offset?
  81247. if (parentCamera.deviceScaleFactor !== 1) {
  81248. this._webvrViewMatrix.invert();
  81249. // scale the position, if set
  81250. if (parentCamera.deviceScaleFactor) {
  81251. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  81252. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  81253. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  81254. }
  81255. this._webvrViewMatrix.invert();
  81256. }
  81257. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  81258. return this._webvrViewMatrix;
  81259. };
  81260. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  81261. var _this = this;
  81262. var parentCamera = this.parent;
  81263. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  81264. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  81265. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  81266. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  81267. //babylon compatible matrix
  81268. if (!this.getScene().useRightHandedSystem) {
  81269. [8, 9, 10, 11].forEach(function (num) {
  81270. _this._projectionMatrix.m[num] *= -1;
  81271. });
  81272. }
  81273. return this._projectionMatrix;
  81274. };
  81275. /**
  81276. * Initializes the controllers and their meshes
  81277. */
  81278. WebVRFreeCamera.prototype.initControllers = function () {
  81279. var _this = this;
  81280. this.controllers = [];
  81281. var manager = this.getScene().gamepadManager;
  81282. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81283. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81284. var webVrController = gamepad;
  81285. if (webVrController.defaultModel) {
  81286. webVrController.defaultModel.setEnabled(false);
  81287. }
  81288. if (webVrController.hand === "right") {
  81289. _this._rightController = null;
  81290. }
  81291. if (webVrController.hand === "left") {
  81292. _this._leftController = null;
  81293. }
  81294. var controllerIndex = _this.controllers.indexOf(webVrController);
  81295. if (controllerIndex !== -1) {
  81296. _this.controllers.splice(controllerIndex, 1);
  81297. }
  81298. }
  81299. });
  81300. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81301. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81302. var webVrController_1 = gamepad;
  81303. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  81304. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  81305. if (_this.webVROptions.controllerMeshes) {
  81306. if (webVrController_1.defaultModel) {
  81307. webVrController_1.defaultModel.setEnabled(true);
  81308. }
  81309. else {
  81310. // Load the meshes
  81311. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  81312. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  81313. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  81314. if (_this.webVROptions.defaultLightingOnControllers) {
  81315. if (!_this._lightOnControllers) {
  81316. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  81317. }
  81318. var activateLightOnSubMeshes_1 = function (mesh, light) {
  81319. var children = mesh.getChildren();
  81320. if (children.length !== 0) {
  81321. children.forEach(function (mesh) {
  81322. light.includedOnlyMeshes.push(mesh);
  81323. activateLightOnSubMeshes_1(mesh, light);
  81324. });
  81325. }
  81326. };
  81327. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  81328. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  81329. }
  81330. });
  81331. }
  81332. }
  81333. webVrController_1.attachToPoseControlledCamera(_this);
  81334. // since this is async - sanity check. Is the controller already stored?
  81335. if (_this.controllers.indexOf(webVrController_1) === -1) {
  81336. //add to the controllers array
  81337. _this.controllers.push(webVrController_1);
  81338. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  81339. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  81340. // So we're overriding setting left & right manually to be sure
  81341. var firstViveWandDetected = false;
  81342. for (var i = 0; i < _this.controllers.length; i++) {
  81343. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  81344. if (!firstViveWandDetected) {
  81345. firstViveWandDetected = true;
  81346. _this.controllers[i].hand = "left";
  81347. }
  81348. else {
  81349. _this.controllers[i].hand = "right";
  81350. }
  81351. }
  81352. }
  81353. //did we find enough controllers? Great! let the developer know.
  81354. if (_this.controllers.length >= 2) {
  81355. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  81356. }
  81357. }
  81358. }
  81359. });
  81360. };
  81361. return WebVRFreeCamera;
  81362. }(BABYLON.FreeCamera));
  81363. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  81364. })(BABYLON || (BABYLON = {}));
  81365. //# sourceMappingURL=babylon.webVRCamera.js.map
  81366. "use strict";
  81367. var BABYLON;
  81368. (function (BABYLON) {
  81369. // We're mainly based on the logic defined into the FreeCamera code
  81370. /**
  81371. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  81372. * being tilted forward or back and left or right.
  81373. */
  81374. var DeviceOrientationCamera = /** @class */ (function (_super) {
  81375. __extends(DeviceOrientationCamera, _super);
  81376. /**
  81377. * Creates a new device orientation camera. @see DeviceOrientationCamera
  81378. * @param name The name of the camera
  81379. * @param position The start position camera
  81380. * @param scene The scene the camera belongs to
  81381. */
  81382. function DeviceOrientationCamera(name, position, scene) {
  81383. var _this = _super.call(this, name, position, scene) || this;
  81384. _this._quaternionCache = new BABYLON.Quaternion();
  81385. _this.inputs.addDeviceOrientation();
  81386. return _this;
  81387. }
  81388. /**
  81389. * Gets the current instance class name ("DeviceOrientationCamera").
  81390. * This helps avoiding instanceof at run time.
  81391. * @returns the class name
  81392. */
  81393. DeviceOrientationCamera.prototype.getClassName = function () {
  81394. return "DeviceOrientationCamera";
  81395. };
  81396. /**
  81397. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  81398. */
  81399. DeviceOrientationCamera.prototype._checkInputs = function () {
  81400. _super.prototype._checkInputs.call(this);
  81401. this._quaternionCache.copyFrom(this.rotationQuaternion);
  81402. if (this._initialQuaternion) {
  81403. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81404. }
  81405. };
  81406. /**
  81407. * Reset the camera to its default orientation on the specified axis only.
  81408. * @param axis The axis to reset
  81409. */
  81410. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  81411. var _this = this;
  81412. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  81413. //can only work if this camera has a rotation quaternion already.
  81414. if (!this.rotationQuaternion)
  81415. return;
  81416. if (!this._initialQuaternion) {
  81417. this._initialQuaternion = new BABYLON.Quaternion();
  81418. }
  81419. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  81420. ['x', 'y', 'z'].forEach(function (axisName) {
  81421. if (!axis[axisName]) {
  81422. _this._initialQuaternion[axisName] = 0;
  81423. }
  81424. else {
  81425. _this._initialQuaternion[axisName] *= -1;
  81426. }
  81427. });
  81428. this._initialQuaternion.normalize();
  81429. //force rotation update
  81430. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  81431. };
  81432. return DeviceOrientationCamera;
  81433. }(BABYLON.FreeCamera));
  81434. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  81435. })(BABYLON || (BABYLON = {}));
  81436. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  81437. "use strict";
  81438. var BABYLON;
  81439. (function (BABYLON) {
  81440. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  81441. __extends(VRDeviceOrientationFreeCamera, _super);
  81442. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81443. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81444. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81445. var _this = _super.call(this, name, position, scene) || this;
  81446. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81447. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81448. return _this;
  81449. }
  81450. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  81451. return "VRDeviceOrientationFreeCamera";
  81452. };
  81453. return VRDeviceOrientationFreeCamera;
  81454. }(BABYLON.DeviceOrientationCamera));
  81455. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  81456. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  81457. __extends(VRDeviceOrientationGamepadCamera, _super);
  81458. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  81459. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81460. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81461. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  81462. _this.inputs.addGamepad();
  81463. return _this;
  81464. }
  81465. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  81466. return "VRDeviceOrientationGamepadCamera";
  81467. };
  81468. return VRDeviceOrientationGamepadCamera;
  81469. }(VRDeviceOrientationFreeCamera));
  81470. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  81471. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  81472. __extends(VRDeviceOrientationArcRotateCamera, _super);
  81473. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  81474. if (compensateDistortion === void 0) { compensateDistortion = true; }
  81475. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  81476. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81477. vrCameraMetrics.compensateDistortion = compensateDistortion;
  81478. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  81479. _this.inputs.addVRDeviceOrientation();
  81480. return _this;
  81481. }
  81482. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  81483. return "VRDeviceOrientationArcRotateCamera";
  81484. };
  81485. return VRDeviceOrientationArcRotateCamera;
  81486. }(BABYLON.ArcRotateCamera));
  81487. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  81488. })(BABYLON || (BABYLON = {}));
  81489. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  81490. "use strict";
  81491. var BABYLON;
  81492. (function (BABYLON) {
  81493. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  81494. __extends(AnaglyphFreeCamera, _super);
  81495. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  81496. var _this = _super.call(this, name, position, scene) || this;
  81497. _this.interaxialDistance = interaxialDistance;
  81498. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81499. return _this;
  81500. }
  81501. AnaglyphFreeCamera.prototype.getClassName = function () {
  81502. return "AnaglyphFreeCamera";
  81503. };
  81504. return AnaglyphFreeCamera;
  81505. }(BABYLON.FreeCamera));
  81506. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  81507. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  81508. __extends(AnaglyphArcRotateCamera, _super);
  81509. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  81510. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81511. _this.interaxialDistance = interaxialDistance;
  81512. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81513. return _this;
  81514. }
  81515. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  81516. return "AnaglyphArcRotateCamera";
  81517. };
  81518. return AnaglyphArcRotateCamera;
  81519. }(BABYLON.ArcRotateCamera));
  81520. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  81521. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  81522. __extends(AnaglyphGamepadCamera, _super);
  81523. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  81524. var _this = _super.call(this, name, position, scene) || this;
  81525. _this.interaxialDistance = interaxialDistance;
  81526. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81527. return _this;
  81528. }
  81529. AnaglyphGamepadCamera.prototype.getClassName = function () {
  81530. return "AnaglyphGamepadCamera";
  81531. };
  81532. return AnaglyphGamepadCamera;
  81533. }(BABYLON.GamepadCamera));
  81534. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  81535. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  81536. __extends(AnaglyphUniversalCamera, _super);
  81537. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  81538. var _this = _super.call(this, name, position, scene) || this;
  81539. _this.interaxialDistance = interaxialDistance;
  81540. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  81541. return _this;
  81542. }
  81543. AnaglyphUniversalCamera.prototype.getClassName = function () {
  81544. return "AnaglyphUniversalCamera";
  81545. };
  81546. return AnaglyphUniversalCamera;
  81547. }(BABYLON.UniversalCamera));
  81548. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  81549. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  81550. __extends(StereoscopicFreeCamera, _super);
  81551. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81552. var _this = _super.call(this, name, position, scene) || this;
  81553. _this.interaxialDistance = interaxialDistance;
  81554. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81555. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81556. return _this;
  81557. }
  81558. StereoscopicFreeCamera.prototype.getClassName = function () {
  81559. return "StereoscopicFreeCamera";
  81560. };
  81561. return StereoscopicFreeCamera;
  81562. }(BABYLON.FreeCamera));
  81563. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  81564. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  81565. __extends(StereoscopicArcRotateCamera, _super);
  81566. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  81567. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  81568. _this.interaxialDistance = interaxialDistance;
  81569. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81570. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81571. return _this;
  81572. }
  81573. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  81574. return "StereoscopicArcRotateCamera";
  81575. };
  81576. return StereoscopicArcRotateCamera;
  81577. }(BABYLON.ArcRotateCamera));
  81578. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  81579. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  81580. __extends(StereoscopicGamepadCamera, _super);
  81581. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81582. var _this = _super.call(this, name, position, scene) || this;
  81583. _this.interaxialDistance = interaxialDistance;
  81584. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81585. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81586. return _this;
  81587. }
  81588. StereoscopicGamepadCamera.prototype.getClassName = function () {
  81589. return "StereoscopicGamepadCamera";
  81590. };
  81591. return StereoscopicGamepadCamera;
  81592. }(BABYLON.GamepadCamera));
  81593. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  81594. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  81595. __extends(StereoscopicUniversalCamera, _super);
  81596. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  81597. var _this = _super.call(this, name, position, scene) || this;
  81598. _this.interaxialDistance = interaxialDistance;
  81599. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  81600. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  81601. return _this;
  81602. }
  81603. StereoscopicUniversalCamera.prototype.getClassName = function () {
  81604. return "StereoscopicUniversalCamera";
  81605. };
  81606. return StereoscopicUniversalCamera;
  81607. }(BABYLON.UniversalCamera));
  81608. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  81609. })(BABYLON || (BABYLON = {}));
  81610. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  81611. "use strict";
  81612. var BABYLON;
  81613. (function (BABYLON) {
  81614. var VRExperienceHelperGazer = /** @class */ (function () {
  81615. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  81616. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  81617. this.scene = scene;
  81618. this._pointerDownOnMeshAsked = false;
  81619. this._isActionableMesh = false;
  81620. this._teleportationRequestInitiated = false;
  81621. this._teleportationBackRequestInitiated = false;
  81622. this._dpadPressed = true;
  81623. this._activePointer = false;
  81624. this._id = VRExperienceHelperGazer._idCounter++;
  81625. // Gaze tracker
  81626. if (!gazeTrackerToClone) {
  81627. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  81628. this._gazeTracker.bakeCurrentTransformIntoVertices();
  81629. this._gazeTracker.isPickable = false;
  81630. this._gazeTracker.isVisible = false;
  81631. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  81632. targetMat.specularColor = BABYLON.Color3.Black();
  81633. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81634. targetMat.backFaceCulling = false;
  81635. this._gazeTracker.material = targetMat;
  81636. }
  81637. else {
  81638. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  81639. }
  81640. }
  81641. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  81642. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  81643. };
  81644. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  81645. this._pointerDownOnMeshAsked = true;
  81646. if (this._currentMeshSelected && this._currentHit) {
  81647. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  81648. }
  81649. };
  81650. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  81651. if (this._currentMeshSelected && this._currentHit) {
  81652. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  81653. }
  81654. this._pointerDownOnMeshAsked = false;
  81655. };
  81656. VRExperienceHelperGazer.prototype._activatePointer = function () {
  81657. this._activePointer = true;
  81658. };
  81659. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  81660. this._activePointer = false;
  81661. };
  81662. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  81663. };
  81664. VRExperienceHelperGazer.prototype.dispose = function () {
  81665. this._interactionsEnabled = false;
  81666. this._teleportationEnabled = false;
  81667. };
  81668. VRExperienceHelperGazer._idCounter = 0;
  81669. return VRExperienceHelperGazer;
  81670. }());
  81671. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  81672. __extends(VRExperienceHelperControllerGazer, _super);
  81673. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  81674. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  81675. _this.webVRController = webVRController;
  81676. // Laser pointer
  81677. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  81678. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  81679. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  81680. laserPointerMaterial.alpha = 0.6;
  81681. _this._laserPointer.material = laserPointerMaterial;
  81682. _this._laserPointer.rotation.x = Math.PI / 2;
  81683. _this._laserPointer.position.z = -0.5;
  81684. _this._laserPointer.isVisible = false;
  81685. if (!webVRController.mesh) {
  81686. // Create an empty mesh that is used prior to loading the high quality model
  81687. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  81688. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  81689. preloadPointerPose.rotation.x = -0.7;
  81690. preloadMesh.addChild(preloadPointerPose);
  81691. webVRController.attachToMesh(preloadMesh);
  81692. }
  81693. _this._setLaserPointerParent(webVRController.mesh);
  81694. return _this;
  81695. }
  81696. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  81697. return this.webVRController.getForwardRay(length);
  81698. };
  81699. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  81700. _super.prototype._activatePointer.call(this);
  81701. this._laserPointer.isVisible = true;
  81702. };
  81703. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  81704. _super.prototype._deactivatePointer.call(this);
  81705. this._laserPointer.isVisible = false;
  81706. };
  81707. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  81708. this._laserPointer.material.emissiveColor = color;
  81709. };
  81710. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  81711. var makeNotPick = function (root) {
  81712. root.name += " laserPointer";
  81713. root.getChildMeshes().forEach(function (c) {
  81714. makeNotPick(c);
  81715. });
  81716. };
  81717. makeNotPick(mesh);
  81718. var childMeshes = mesh.getChildMeshes();
  81719. this.webVRController._pointingPoseNode = null;
  81720. for (var i = 0; i < childMeshes.length; i++) {
  81721. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  81722. mesh = childMeshes[i];
  81723. this.webVRController._pointingPoseNode = mesh;
  81724. break;
  81725. }
  81726. }
  81727. this._laserPointer.parent = mesh;
  81728. };
  81729. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  81730. this._laserPointer.scaling.y = distance;
  81731. this._laserPointer.position.z = -distance / 2;
  81732. };
  81733. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  81734. _super.prototype.dispose.call(this);
  81735. this._laserPointer.dispose();
  81736. };
  81737. return VRExperienceHelperControllerGazer;
  81738. }(VRExperienceHelperGazer));
  81739. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  81740. __extends(VRExperienceHelperCameraGazer, _super);
  81741. function VRExperienceHelperCameraGazer(getCamera, scene) {
  81742. var _this = _super.call(this, scene) || this;
  81743. _this.getCamera = getCamera;
  81744. return _this;
  81745. }
  81746. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  81747. var camera = this.getCamera();
  81748. if (camera) {
  81749. return camera.getForwardRay(length);
  81750. }
  81751. else {
  81752. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  81753. }
  81754. };
  81755. return VRExperienceHelperCameraGazer;
  81756. }(VRExperienceHelperGazer));
  81757. /**
  81758. * Helps to quickly add VR support to an existing scene.
  81759. * See http://doc.babylonjs.com/how_to/webvr_helper
  81760. */
  81761. var VRExperienceHelper = /** @class */ (function () {
  81762. /**
  81763. * Instantiates a VRExperienceHelper.
  81764. * Helps to quickly add VR support to an existing scene.
  81765. * @param scene The scene the VRExperienceHelper belongs to.
  81766. * @param webVROptions Options to modify the vr experience helper's behavior.
  81767. */
  81768. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  81769. if (webVROptions === void 0) { webVROptions = {}; }
  81770. var _this = this;
  81771. this.webVROptions = webVROptions;
  81772. // Can the system support WebVR, even if a headset isn't plugged in?
  81773. this._webVRsupported = false;
  81774. // If WebVR is supported, is a headset plugged in and are we ready to present?
  81775. this._webVRready = false;
  81776. // Are we waiting for the requestPresent callback to complete?
  81777. this._webVRrequesting = false;
  81778. // Are we presenting to the headset right now?
  81779. this._webVRpresenting = false;
  81780. // Are we presenting in the fullscreen fallback?
  81781. this._fullscreenVRpresenting = false;
  81782. /**
  81783. * Observable raised when entering VR.
  81784. */
  81785. this.onEnteringVRObservable = new BABYLON.Observable();
  81786. /**
  81787. * Observable raised when exiting VR.
  81788. */
  81789. this.onExitingVRObservable = new BABYLON.Observable();
  81790. /**
  81791. * Observable raised when controller mesh is loaded.
  81792. */
  81793. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81794. this._useCustomVRButton = false;
  81795. this._teleportationRequested = false;
  81796. this._teleportActive = false;
  81797. this._floorMeshesCollection = [];
  81798. this._rotationAllowed = true;
  81799. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  81800. this._rotationRightAsked = false;
  81801. this._rotationLeftAsked = false;
  81802. this._isDefaultTeleportationTarget = true;
  81803. this._teleportationFillColor = "#444444";
  81804. this._teleportationBorderColor = "#FFFFFF";
  81805. this._rotationAngle = 0;
  81806. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  81807. this._padSensibilityUp = 0.65;
  81808. this._padSensibilityDown = 0.35;
  81809. this.leftController = null;
  81810. this.rightController = null;
  81811. /**
  81812. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  81813. */
  81814. this.onNewMeshSelected = new BABYLON.Observable();
  81815. /**
  81816. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  81817. */
  81818. this.onNewMeshPicked = new BABYLON.Observable();
  81819. /**
  81820. * Observable raised before camera teleportation
  81821. */
  81822. this.onBeforeCameraTeleport = new BABYLON.Observable();
  81823. /**
  81824. * Observable raised after camera teleportation
  81825. */
  81826. this.onAfterCameraTeleport = new BABYLON.Observable();
  81827. /**
  81828. * Observable raised when current selected mesh gets unselected
  81829. */
  81830. this.onSelectedMeshUnselected = new BABYLON.Observable();
  81831. /**
  81832. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  81833. */
  81834. this.teleportationEnabled = true;
  81835. this._teleportationInitialized = false;
  81836. this._interactionsEnabled = false;
  81837. this._interactionsRequested = false;
  81838. this._displayGaze = true;
  81839. this._displayLaserPointer = true;
  81840. this._onResize = function () {
  81841. _this.moveButtonToBottomRight();
  81842. if (_this._fullscreenVRpresenting && _this._webVRready) {
  81843. _this.exitVR();
  81844. }
  81845. };
  81846. this._onFullscreenChange = function () {
  81847. if (document.fullscreen !== undefined) {
  81848. _this._fullscreenVRpresenting = document.fullscreen;
  81849. }
  81850. else if (document.mozFullScreen !== undefined) {
  81851. _this._fullscreenVRpresenting = document.mozFullScreen;
  81852. }
  81853. else if (document.webkitIsFullScreen !== undefined) {
  81854. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  81855. }
  81856. else if (document.msIsFullScreen !== undefined) {
  81857. _this._fullscreenVRpresenting = document.msIsFullScreen;
  81858. }
  81859. if (!_this._fullscreenVRpresenting && _this._canvas) {
  81860. _this.exitVR();
  81861. if (!_this._useCustomVRButton) {
  81862. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  81863. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  81864. }
  81865. }
  81866. };
  81867. this.beforeRender = function () {
  81868. if (_this.leftController && _this.leftController._activePointer) {
  81869. _this._castRayAndSelectObject(_this.leftController);
  81870. }
  81871. if (_this.rightController && _this.rightController._activePointer) {
  81872. _this._castRayAndSelectObject(_this.rightController);
  81873. }
  81874. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  81875. _this._castRayAndSelectObject(_this._cameraGazer);
  81876. }
  81877. else {
  81878. _this._cameraGazer._gazeTracker.isVisible = false;
  81879. }
  81880. };
  81881. this._onNewGamepadConnected = function (gamepad) {
  81882. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  81883. if (gamepad.leftStick) {
  81884. gamepad.onleftstickchanged(function (stickValues) {
  81885. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  81886. // Listening to classic/xbox gamepad only if no VR controller is active
  81887. if ((!_this.leftController && !_this.rightController) ||
  81888. ((_this.leftController && !_this.leftController._activePointer) &&
  81889. (_this.rightController && !_this.rightController._activePointer))) {
  81890. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  81891. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  81892. }
  81893. }
  81894. });
  81895. }
  81896. if (gamepad.rightStick) {
  81897. gamepad.onrightstickchanged(function (stickValues) {
  81898. if (_this._teleportationInitialized) {
  81899. _this._checkRotate(stickValues, _this._cameraGazer);
  81900. }
  81901. });
  81902. }
  81903. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  81904. gamepad.onbuttondown(function (buttonPressed) {
  81905. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81906. _this._cameraGazer._selectionPointerDown();
  81907. }
  81908. });
  81909. gamepad.onbuttonup(function (buttonPressed) {
  81910. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  81911. _this._cameraGazer._selectionPointerUp();
  81912. }
  81913. });
  81914. }
  81915. }
  81916. else {
  81917. var webVRController = gamepad;
  81918. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  81919. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  81920. _this.rightController = controller;
  81921. }
  81922. else {
  81923. _this.leftController = controller;
  81924. }
  81925. _this._tryEnableInteractionOnController(controller);
  81926. }
  81927. };
  81928. // 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
  81929. this._tryEnableInteractionOnController = function (controller) {
  81930. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  81931. _this._enableInteractionOnController(controller);
  81932. }
  81933. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  81934. _this._enableTeleportationOnController(controller);
  81935. }
  81936. };
  81937. this._onNewGamepadDisconnected = function (gamepad) {
  81938. if (gamepad instanceof BABYLON.WebVRController) {
  81939. if (gamepad.hand === "left" && _this.leftController != null) {
  81940. _this.leftController.dispose();
  81941. _this.leftController = null;
  81942. }
  81943. if (gamepad.hand === "right" && _this.rightController != null) {
  81944. _this.rightController.dispose();
  81945. _this.rightController = null;
  81946. }
  81947. }
  81948. };
  81949. this._workingVector = BABYLON.Vector3.Zero();
  81950. this._workingQuaternion = BABYLON.Quaternion.Identity();
  81951. this._workingMatrix = BABYLON.Matrix.Identity();
  81952. this._scene = scene;
  81953. this._canvas = scene.getEngine().getRenderingCanvas();
  81954. // Parse options
  81955. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  81956. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  81957. }
  81958. if (webVROptions.createDeviceOrientationCamera === undefined) {
  81959. webVROptions.createDeviceOrientationCamera = true;
  81960. }
  81961. if (webVROptions.defaultHeight === undefined) {
  81962. webVROptions.defaultHeight = 1.7;
  81963. }
  81964. if (webVROptions.useCustomVRButton) {
  81965. this._useCustomVRButton = true;
  81966. if (webVROptions.customVRButton) {
  81967. this._btnVR = webVROptions.customVRButton;
  81968. }
  81969. }
  81970. if (webVROptions.rayLength) {
  81971. this._rayLength = webVROptions.rayLength;
  81972. }
  81973. this._defaultHeight = webVROptions.defaultHeight;
  81974. if (webVROptions.positionScale) {
  81975. this._rayLength *= webVROptions.positionScale;
  81976. this._defaultHeight *= webVROptions.positionScale;
  81977. }
  81978. // Set position
  81979. if (this._scene.activeCamera) {
  81980. this._position = this._scene.activeCamera.position.clone();
  81981. }
  81982. else {
  81983. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  81984. }
  81985. // Set non-vr camera
  81986. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  81987. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  81988. // Copy data from existing camera
  81989. if (this._scene.activeCamera) {
  81990. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  81991. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  81992. // Set rotation from previous camera
  81993. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  81994. var targetCamera = this._scene.activeCamera;
  81995. if (targetCamera.rotationQuaternion) {
  81996. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  81997. }
  81998. else {
  81999. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  82000. }
  82001. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  82002. }
  82003. }
  82004. this._scene.activeCamera = this._deviceOrientationCamera;
  82005. if (this._canvas) {
  82006. this._scene.activeCamera.attachControl(this._canvas);
  82007. }
  82008. }
  82009. else {
  82010. this._existingCamera = this._scene.activeCamera;
  82011. }
  82012. // Create VR cameras
  82013. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82014. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  82015. }
  82016. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  82017. this._webVRCamera.useStandingMatrix();
  82018. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  82019. // Create default button
  82020. if (!this._useCustomVRButton) {
  82021. this._btnVR = document.createElement("BUTTON");
  82022. this._btnVR.className = "babylonVRicon";
  82023. this._btnVR.id = "babylonVRiconbtn";
  82024. this._btnVR.title = "Click to switch to VR";
  82025. 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) }";
  82026. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  82027. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  82028. // css += ".babylonVRicon.vrdisplaysupported { }";
  82029. // css += ".babylonVRicon.vrdisplayready { }";
  82030. // css += ".babylonVRicon.vrdisplayrequesting { }";
  82031. var style = document.createElement('style');
  82032. style.appendChild(document.createTextNode(css));
  82033. document.getElementsByTagName('head')[0].appendChild(style);
  82034. this.moveButtonToBottomRight();
  82035. }
  82036. // VR button click event
  82037. if (this._btnVR) {
  82038. this._btnVR.addEventListener("click", function () {
  82039. if (!_this.isInVRMode) {
  82040. _this.enterVR();
  82041. }
  82042. else {
  82043. _this.exitVR();
  82044. }
  82045. });
  82046. }
  82047. // Window events
  82048. window.addEventListener("resize", this._onResize);
  82049. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  82050. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  82051. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  82052. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  82053. // Display vr button when headset is connected
  82054. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82055. this.displayVRButton();
  82056. }
  82057. else {
  82058. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  82059. if (e.vrDisplay) {
  82060. _this.displayVRButton();
  82061. }
  82062. });
  82063. }
  82064. // Exiting VR mode using 'ESC' key on desktop
  82065. this._onKeyDown = function (event) {
  82066. if (event.keyCode === 27 && _this.isInVRMode) {
  82067. _this.exitVR();
  82068. }
  82069. };
  82070. document.addEventListener("keydown", this._onKeyDown);
  82071. // Exiting VR mode double tapping the touch screen
  82072. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  82073. if (_this.isInVRMode) {
  82074. _this.exitVR();
  82075. if (_this._fullscreenVRpresenting) {
  82076. _this._scene.getEngine().switchFullscreen(true);
  82077. }
  82078. }
  82079. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  82080. // Listen for WebVR display changes
  82081. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  82082. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  82083. this._onVRRequestPresentStart = function () {
  82084. _this._webVRrequesting = true;
  82085. _this.updateButtonVisibility();
  82086. };
  82087. this._onVRRequestPresentComplete = function (success) {
  82088. _this._webVRrequesting = false;
  82089. _this.updateButtonVisibility();
  82090. };
  82091. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  82092. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  82093. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  82094. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82095. scene.onDisposeObservable.add(function () {
  82096. _this.dispose();
  82097. });
  82098. // Gamepad connection events
  82099. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  82100. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  82101. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  82102. this.updateButtonVisibility();
  82103. //create easing functions
  82104. this._circleEase = new BABYLON.CircleEase();
  82105. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82106. }
  82107. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  82108. /** Return this.onEnteringVRObservable
  82109. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  82110. */
  82111. get: function () {
  82112. return this.onEnteringVRObservable;
  82113. },
  82114. enumerable: true,
  82115. configurable: true
  82116. });
  82117. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  82118. /** Return this.onExitingVRObservable
  82119. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  82120. */
  82121. get: function () {
  82122. return this.onExitingVRObservable;
  82123. },
  82124. enumerable: true,
  82125. configurable: true
  82126. });
  82127. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  82128. /** Return this.onControllerMeshLoadedObservable
  82129. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  82130. */
  82131. get: function () {
  82132. return this.onControllerMeshLoadedObservable;
  82133. },
  82134. enumerable: true,
  82135. configurable: true
  82136. });
  82137. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  82138. /**
  82139. * The mesh used to display where the user is going to teleport.
  82140. */
  82141. get: function () {
  82142. return this._teleportationTarget;
  82143. },
  82144. /**
  82145. * Sets the mesh to be used to display where the user is going to teleport.
  82146. */
  82147. set: function (value) {
  82148. if (value) {
  82149. value.name = "teleportationTarget";
  82150. this._isDefaultTeleportationTarget = false;
  82151. this._teleportationTarget = value;
  82152. }
  82153. },
  82154. enumerable: true,
  82155. configurable: true
  82156. });
  82157. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  82158. /**
  82159. * The mesh used to display where the user is selecting,
  82160. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  82161. * See http://doc.babylonjs.com/resources/baking_transformations
  82162. */
  82163. get: function () {
  82164. return this._cameraGazer._gazeTracker;
  82165. },
  82166. set: function (value) {
  82167. if (value) {
  82168. this._cameraGazer._gazeTracker = value;
  82169. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  82170. this._cameraGazer._gazeTracker.isPickable = false;
  82171. this._cameraGazer._gazeTracker.isVisible = false;
  82172. this._cameraGazer._gazeTracker.name = "gazeTracker";
  82173. if (this.leftController) {
  82174. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82175. }
  82176. if (this.rightController) {
  82177. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82178. }
  82179. }
  82180. },
  82181. enumerable: true,
  82182. configurable: true
  82183. });
  82184. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82185. /**
  82186. * If the ray of the gaze should be displayed.
  82187. */
  82188. get: function () {
  82189. return this._displayGaze;
  82190. },
  82191. /**
  82192. * Sets if the ray of the gaze should be displayed.
  82193. */
  82194. set: function (value) {
  82195. this._displayGaze = value;
  82196. if (!value) {
  82197. this._cameraGazer._gazeTracker.isVisible = false;
  82198. if (this.leftController) {
  82199. this.leftController._gazeTracker.isVisible = false;
  82200. }
  82201. if (this.rightController) {
  82202. this.rightController._gazeTracker.isVisible = false;
  82203. }
  82204. }
  82205. },
  82206. enumerable: true,
  82207. configurable: true
  82208. });
  82209. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82210. /**
  82211. * If the ray of the LaserPointer should be displayed.
  82212. */
  82213. get: function () {
  82214. return this._displayLaserPointer;
  82215. },
  82216. /**
  82217. * Sets if the ray of the LaserPointer should be displayed.
  82218. */
  82219. set: function (value) {
  82220. this._displayLaserPointer = value;
  82221. if (!value) {
  82222. if (this.rightController) {
  82223. this.rightController._deactivatePointer();
  82224. this.rightController._gazeTracker.isVisible = false;
  82225. }
  82226. if (this.leftController) {
  82227. this.leftController._deactivatePointer();
  82228. this.leftController._gazeTracker.isVisible = false;
  82229. }
  82230. }
  82231. else {
  82232. if (this.rightController) {
  82233. this.rightController._activatePointer();
  82234. }
  82235. else if (this.leftController) {
  82236. this.leftController._activatePointer();
  82237. }
  82238. }
  82239. },
  82240. enumerable: true,
  82241. configurable: true
  82242. });
  82243. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  82244. /**
  82245. * The deviceOrientationCamera used as the camera when not in VR.
  82246. */
  82247. get: function () {
  82248. return this._deviceOrientationCamera;
  82249. },
  82250. enumerable: true,
  82251. configurable: true
  82252. });
  82253. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  82254. /**
  82255. * Based on the current WebVR support, returns the current VR camera used.
  82256. */
  82257. get: function () {
  82258. if (this._webVRready) {
  82259. return this._webVRCamera;
  82260. }
  82261. else {
  82262. return this._scene.activeCamera;
  82263. }
  82264. },
  82265. enumerable: true,
  82266. configurable: true
  82267. });
  82268. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  82269. /**
  82270. * The webVRCamera which is used when in VR.
  82271. */
  82272. get: function () {
  82273. return this._webVRCamera;
  82274. },
  82275. enumerable: true,
  82276. configurable: true
  82277. });
  82278. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  82279. /**
  82280. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  82281. */
  82282. get: function () {
  82283. return this._vrDeviceOrientationCamera;
  82284. },
  82285. enumerable: true,
  82286. configurable: true
  82287. });
  82288. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  82289. get: function () {
  82290. var result = this._cameraGazer._teleportationRequestInitiated
  82291. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  82292. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  82293. return result;
  82294. },
  82295. enumerable: true,
  82296. configurable: true
  82297. });
  82298. // Raised when one of the controller has loaded successfully its associated default mesh
  82299. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  82300. if (this.leftController && this.leftController.webVRController == webVRController) {
  82301. if (webVRController.mesh) {
  82302. this.leftController._setLaserPointerParent(webVRController.mesh);
  82303. }
  82304. }
  82305. if (this.rightController && this.rightController.webVRController == webVRController) {
  82306. if (webVRController.mesh) {
  82307. this.rightController._setLaserPointerParent(webVRController.mesh);
  82308. }
  82309. }
  82310. try {
  82311. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  82312. }
  82313. catch (err) {
  82314. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  82315. }
  82316. };
  82317. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  82318. /**
  82319. * Gets a value indicating if we are currently in VR mode.
  82320. */
  82321. get: function () {
  82322. return this._webVRpresenting || this._fullscreenVRpresenting;
  82323. },
  82324. enumerable: true,
  82325. configurable: true
  82326. });
  82327. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  82328. var vrDisplay = this._scene.getEngine().getVRDevice();
  82329. if (vrDisplay) {
  82330. var wasPresenting = this._webVRpresenting;
  82331. // A VR display is connected
  82332. this._webVRpresenting = vrDisplay.isPresenting;
  82333. if (wasPresenting && !this._webVRpresenting)
  82334. this.exitVR();
  82335. }
  82336. else {
  82337. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  82338. }
  82339. this.updateButtonVisibility();
  82340. };
  82341. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  82342. this._webVRsupported = eventArgs.vrSupported;
  82343. this._webVRready = !!eventArgs.vrDisplay;
  82344. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  82345. this.updateButtonVisibility();
  82346. };
  82347. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  82348. if (this._canvas && !this._useCustomVRButton) {
  82349. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  82350. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  82351. }
  82352. };
  82353. VRExperienceHelper.prototype.displayVRButton = function () {
  82354. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  82355. document.body.appendChild(this._btnVR);
  82356. this._btnVRDisplayed = true;
  82357. }
  82358. };
  82359. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  82360. if (!this._btnVR || this._useCustomVRButton) {
  82361. return;
  82362. }
  82363. this._btnVR.className = "babylonVRicon";
  82364. if (this.isInVRMode) {
  82365. this._btnVR.className += " vrdisplaypresenting";
  82366. }
  82367. else {
  82368. if (this._webVRready)
  82369. this._btnVR.className += " vrdisplayready";
  82370. if (this._webVRsupported)
  82371. this._btnVR.className += " vrdisplaysupported";
  82372. if (this._webVRrequesting)
  82373. this._btnVR.className += " vrdisplayrequesting";
  82374. }
  82375. };
  82376. /**
  82377. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  82378. * Otherwise, will use the fullscreen API.
  82379. */
  82380. VRExperienceHelper.prototype.enterVR = function () {
  82381. if (this.onEnteringVRObservable) {
  82382. try {
  82383. this.onEnteringVRObservable.notifyObservers(this);
  82384. }
  82385. catch (err) {
  82386. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  82387. }
  82388. }
  82389. if (this._scene.activeCamera) {
  82390. this._position = this._scene.activeCamera.position.clone();
  82391. // make sure that we return to the last active camera
  82392. this._existingCamera = this._scene.activeCamera;
  82393. }
  82394. if (this._webVRrequesting)
  82395. return;
  82396. // If WebVR is supported and a headset is connected
  82397. if (this._webVRready) {
  82398. if (!this._webVRpresenting) {
  82399. this._webVRCamera.position = this._position;
  82400. this._scene.activeCamera = this._webVRCamera;
  82401. }
  82402. }
  82403. else if (this._vrDeviceOrientationCamera) {
  82404. this._vrDeviceOrientationCamera.position = this._position;
  82405. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  82406. this._scene.getEngine().switchFullscreen(true);
  82407. this.updateButtonVisibility();
  82408. }
  82409. if (this._scene.activeCamera && this._canvas) {
  82410. this._scene.activeCamera.attachControl(this._canvas);
  82411. }
  82412. if (this._interactionsEnabled) {
  82413. this._scene.registerBeforeRender(this.beforeRender);
  82414. }
  82415. };
  82416. /**
  82417. * Attempt to exit VR, or fullscreen.
  82418. */
  82419. VRExperienceHelper.prototype.exitVR = function () {
  82420. if (this.onExitingVRObservable) {
  82421. try {
  82422. this.onExitingVRObservable.notifyObservers(this);
  82423. }
  82424. catch (err) {
  82425. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  82426. }
  82427. }
  82428. if (this._webVRpresenting) {
  82429. this._scene.getEngine().disableVR();
  82430. }
  82431. if (this._scene.activeCamera) {
  82432. this._position = this._scene.activeCamera.position.clone();
  82433. }
  82434. if (this._deviceOrientationCamera) {
  82435. this._deviceOrientationCamera.position = this._position;
  82436. this._scene.activeCamera = this._deviceOrientationCamera;
  82437. if (this._canvas) {
  82438. this._scene.activeCamera.attachControl(this._canvas);
  82439. }
  82440. }
  82441. else if (this._existingCamera) {
  82442. this._existingCamera.position = this._position;
  82443. this._scene.activeCamera = this._existingCamera;
  82444. }
  82445. this.updateButtonVisibility();
  82446. if (this._interactionsEnabled) {
  82447. this._scene.unregisterBeforeRender(this.beforeRender);
  82448. }
  82449. };
  82450. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  82451. /**
  82452. * The position of the vr experience helper.
  82453. */
  82454. get: function () {
  82455. return this._position;
  82456. },
  82457. /**
  82458. * Sets the position of the vr experience helper.
  82459. */
  82460. set: function (value) {
  82461. this._position = value;
  82462. if (this._scene.activeCamera) {
  82463. this._scene.activeCamera.position = value;
  82464. }
  82465. },
  82466. enumerable: true,
  82467. configurable: true
  82468. });
  82469. /**
  82470. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  82471. */
  82472. VRExperienceHelper.prototype.enableInteractions = function () {
  82473. var _this = this;
  82474. if (!this._interactionsEnabled) {
  82475. this._interactionsRequested = true;
  82476. if (this.leftController) {
  82477. this._enableInteractionOnController(this.leftController);
  82478. }
  82479. if (this.rightController) {
  82480. this._enableInteractionOnController(this.rightController);
  82481. }
  82482. this.raySelectionPredicate = function (mesh) {
  82483. return mesh.isVisible;
  82484. };
  82485. this.meshSelectionPredicate = function (mesh) {
  82486. return true;
  82487. };
  82488. this._raySelectionPredicate = function (mesh) {
  82489. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  82490. && mesh.name.indexOf("teleportationTarget") === -1
  82491. && mesh.name.indexOf("torusTeleportation") === -1
  82492. && mesh.name.indexOf("laserPointer") === -1)) {
  82493. return _this.raySelectionPredicate(mesh);
  82494. }
  82495. return false;
  82496. };
  82497. this._interactionsEnabled = true;
  82498. }
  82499. };
  82500. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  82501. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  82502. if (this._floorMeshesCollection[i].id === mesh.id) {
  82503. return true;
  82504. }
  82505. }
  82506. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  82507. return true;
  82508. }
  82509. return false;
  82510. };
  82511. /**
  82512. * Adds a floor mesh to be used for teleportation.
  82513. * @param floorMesh the mesh to be used for teleportation.
  82514. */
  82515. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  82516. if (!this._floorMeshesCollection) {
  82517. return;
  82518. }
  82519. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  82520. return;
  82521. }
  82522. this._floorMeshesCollection.push(floorMesh);
  82523. };
  82524. /**
  82525. * Removes a floor mesh from being used for teleportation.
  82526. * @param floorMesh the mesh to be removed.
  82527. */
  82528. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  82529. if (!this._floorMeshesCollection) {
  82530. return;
  82531. }
  82532. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  82533. if (meshIndex !== -1) {
  82534. this._floorMeshesCollection.splice(meshIndex, 1);
  82535. }
  82536. };
  82537. /**
  82538. * Enables interactions and teleportation using the VR controllers and gaze.
  82539. * @param vrTeleportationOptions options to modify teleportation behavior.
  82540. */
  82541. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  82542. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  82543. if (!this._teleportationInitialized) {
  82544. this._teleportationRequested = true;
  82545. this.enableInteractions();
  82546. if (vrTeleportationOptions.floorMeshName) {
  82547. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  82548. }
  82549. if (vrTeleportationOptions.floorMeshes) {
  82550. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  82551. }
  82552. if (this.leftController != null) {
  82553. this._enableTeleportationOnController(this.leftController);
  82554. }
  82555. if (this.rightController != null) {
  82556. this._enableTeleportationOnController(this.rightController);
  82557. }
  82558. // Creates an image processing post process for the vignette not relying
  82559. // on the main scene configuration for image processing to reduce setup and spaces
  82560. // (gamma/linear) conflicts.
  82561. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  82562. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  82563. imageProcessingConfiguration.vignetteEnabled = true;
  82564. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  82565. this._webVRCamera.detachPostProcess(this._postProcessMove);
  82566. this._teleportationInitialized = true;
  82567. if (this._isDefaultTeleportationTarget) {
  82568. this._createTeleportationCircles();
  82569. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  82570. }
  82571. }
  82572. };
  82573. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  82574. var _this = this;
  82575. var controllerMesh = controller.webVRController.mesh;
  82576. if (controllerMesh) {
  82577. controller._interactionsEnabled = true;
  82578. controller._activatePointer();
  82579. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  82580. // Enabling / disabling laserPointer
  82581. if (_this._displayLaserPointer && stateObject.value === 1) {
  82582. if (controller._activePointer) {
  82583. controller._deactivatePointer();
  82584. }
  82585. else {
  82586. controller._activatePointer();
  82587. }
  82588. if (_this.displayGaze) {
  82589. controller._gazeTracker.isVisible = controller._activePointer;
  82590. }
  82591. }
  82592. });
  82593. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  82594. if (!controller._pointerDownOnMeshAsked) {
  82595. if (stateObject.value > _this._padSensibilityUp) {
  82596. controller._selectionPointerDown();
  82597. }
  82598. }
  82599. else if (stateObject.value < _this._padSensibilityDown) {
  82600. controller._selectionPointerUp();
  82601. }
  82602. });
  82603. }
  82604. };
  82605. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  82606. // Dont teleport if another gaze already requested teleportation
  82607. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  82608. return;
  82609. }
  82610. if (!gazer._teleportationRequestInitiated) {
  82611. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  82612. gazer._activatePointer();
  82613. gazer._teleportationRequestInitiated = true;
  82614. }
  82615. }
  82616. else {
  82617. // Listening to the proper controller values changes to confirm teleportation
  82618. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  82619. if (this._teleportActive) {
  82620. this._teleportCamera(this._haloCenter);
  82621. }
  82622. gazer._teleportationRequestInitiated = false;
  82623. }
  82624. }
  82625. };
  82626. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  82627. // Only rotate when user is not currently selecting a teleportation location
  82628. if (gazer._teleportationRequestInitiated) {
  82629. return;
  82630. }
  82631. if (!this._rotationLeftAsked) {
  82632. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  82633. this._rotationLeftAsked = true;
  82634. if (this._rotationAllowed) {
  82635. this._rotateCamera(false);
  82636. }
  82637. }
  82638. }
  82639. else {
  82640. if (stateObject.x > -this._padSensibilityDown) {
  82641. this._rotationLeftAsked = false;
  82642. }
  82643. }
  82644. if (!this._rotationRightAsked) {
  82645. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  82646. this._rotationRightAsked = true;
  82647. if (this._rotationAllowed) {
  82648. this._rotateCamera(true);
  82649. }
  82650. }
  82651. }
  82652. else {
  82653. if (stateObject.x < this._padSensibilityDown) {
  82654. this._rotationRightAsked = false;
  82655. }
  82656. }
  82657. };
  82658. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  82659. // Only teleport backwards when user is not currently selecting a teleportation location
  82660. if (gazer._teleportationRequestInitiated) {
  82661. return;
  82662. }
  82663. // Teleport backwards
  82664. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  82665. if (!gazer._teleportationBackRequestInitiated) {
  82666. if (!this.currentVRCamera) {
  82667. return;
  82668. }
  82669. // Get rotation and position of the current camera
  82670. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  82671. var position = this.currentVRCamera.position;
  82672. // If the camera has device position, use that instead
  82673. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  82674. rotation = this.currentVRCamera.deviceRotationQuaternion;
  82675. position = this.currentVRCamera.devicePosition;
  82676. }
  82677. // Get matrix with only the y rotation of the device rotation
  82678. rotation.toEulerAnglesToRef(this._workingVector);
  82679. this._workingVector.z = 0;
  82680. this._workingVector.x = 0;
  82681. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  82682. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  82683. // Rotate backwards ray by device rotation to cast at the ground behind the user
  82684. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  82685. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  82686. var ray = new BABYLON.Ray(position, this._workingVector);
  82687. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  82688. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  82689. this._teleportCamera(hit.pickedPoint);
  82690. }
  82691. gazer._teleportationBackRequestInitiated = true;
  82692. }
  82693. }
  82694. else {
  82695. gazer._teleportationBackRequestInitiated = false;
  82696. }
  82697. };
  82698. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  82699. var _this = this;
  82700. var controllerMesh = controller.webVRController.mesh;
  82701. if (controllerMesh) {
  82702. if (!controller._interactionsEnabled) {
  82703. this._enableInteractionOnController(controller);
  82704. }
  82705. controller._interactionsEnabled = true;
  82706. controller._teleportationEnabled = true;
  82707. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82708. controller._dpadPressed = false;
  82709. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  82710. controller._dpadPressed = stateObject.pressed;
  82711. if (!controller._dpadPressed) {
  82712. _this._rotationLeftAsked = false;
  82713. _this._rotationRightAsked = false;
  82714. controller._teleportationBackRequestInitiated = false;
  82715. }
  82716. });
  82717. }
  82718. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  82719. if (_this.teleportationEnabled) {
  82720. _this._checkTeleportBackwards(stateObject, controller);
  82721. _this._checkTeleportWithRay(stateObject, controller);
  82722. }
  82723. _this._checkRotate(stateObject, controller);
  82724. });
  82725. }
  82726. };
  82727. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  82728. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  82729. this._teleportationTarget.isPickable = false;
  82730. var length = 512;
  82731. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  82732. dynamicTexture.hasAlpha = true;
  82733. var context = dynamicTexture.getContext();
  82734. var centerX = length / 2;
  82735. var centerY = length / 2;
  82736. var radius = 200;
  82737. context.beginPath();
  82738. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  82739. context.fillStyle = this._teleportationFillColor;
  82740. context.fill();
  82741. context.lineWidth = 10;
  82742. context.strokeStyle = this._teleportationBorderColor;
  82743. context.stroke();
  82744. context.closePath();
  82745. dynamicTexture.update();
  82746. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  82747. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  82748. this._teleportationTarget.material = teleportationCircleMaterial;
  82749. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  82750. torus.isPickable = false;
  82751. torus.parent = this._teleportationTarget;
  82752. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82753. var keys = [];
  82754. keys.push({
  82755. frame: 0,
  82756. value: 0
  82757. });
  82758. keys.push({
  82759. frame: 30,
  82760. value: 0.4
  82761. });
  82762. keys.push({
  82763. frame: 60,
  82764. value: 0
  82765. });
  82766. animationInnerCircle.setKeys(keys);
  82767. var easingFunction = new BABYLON.SineEase();
  82768. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82769. animationInnerCircle.setEasingFunction(easingFunction);
  82770. torus.animations = [];
  82771. torus.animations.push(animationInnerCircle);
  82772. this._scene.beginAnimation(torus, 0, 60, true);
  82773. this._hideTeleportationTarget();
  82774. };
  82775. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  82776. this._teleportActive = true;
  82777. if (this._teleportationInitialized) {
  82778. this._teleportationTarget.isVisible = true;
  82779. if (this._isDefaultTeleportationTarget) {
  82780. this._teleportationTarget.getChildren()[0].isVisible = true;
  82781. }
  82782. }
  82783. };
  82784. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  82785. this._teleportActive = false;
  82786. if (this._teleportationInitialized) {
  82787. this._teleportationTarget.isVisible = false;
  82788. if (this._isDefaultTeleportationTarget) {
  82789. this._teleportationTarget.getChildren()[0].isVisible = false;
  82790. }
  82791. }
  82792. };
  82793. VRExperienceHelper.prototype._rotateCamera = function (right) {
  82794. var _this = this;
  82795. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82796. return;
  82797. }
  82798. if (right) {
  82799. this._rotationAngle++;
  82800. }
  82801. else {
  82802. this._rotationAngle--;
  82803. }
  82804. this.currentVRCamera.animations = [];
  82805. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  82806. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82807. var animationRotationKeys = [];
  82808. animationRotationKeys.push({
  82809. frame: 0,
  82810. value: this.currentVRCamera.rotationQuaternion
  82811. });
  82812. animationRotationKeys.push({
  82813. frame: 6,
  82814. value: target
  82815. });
  82816. animationRotation.setKeys(animationRotationKeys);
  82817. animationRotation.setEasingFunction(this._circleEase);
  82818. this.currentVRCamera.animations.push(animationRotation);
  82819. this._postProcessMove.animations = [];
  82820. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82821. var vignetteWeightKeys = [];
  82822. vignetteWeightKeys.push({
  82823. frame: 0,
  82824. value: 0
  82825. });
  82826. vignetteWeightKeys.push({
  82827. frame: 3,
  82828. value: 4
  82829. });
  82830. vignetteWeightKeys.push({
  82831. frame: 6,
  82832. value: 0
  82833. });
  82834. animationPP.setKeys(vignetteWeightKeys);
  82835. animationPP.setEasingFunction(this._circleEase);
  82836. this._postProcessMove.animations.push(animationPP);
  82837. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82838. var vignetteStretchKeys = [];
  82839. vignetteStretchKeys.push({
  82840. frame: 0,
  82841. value: 0
  82842. });
  82843. vignetteStretchKeys.push({
  82844. frame: 3,
  82845. value: 10
  82846. });
  82847. vignetteStretchKeys.push({
  82848. frame: 6,
  82849. value: 0
  82850. });
  82851. animationPP2.setKeys(vignetteStretchKeys);
  82852. animationPP2.setEasingFunction(this._circleEase);
  82853. this._postProcessMove.animations.push(animationPP2);
  82854. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82855. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82856. this._postProcessMove.samples = 4;
  82857. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82858. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  82859. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82860. });
  82861. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  82862. };
  82863. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  82864. if (hit.pickedPoint) {
  82865. if (gazer._teleportationRequestInitiated) {
  82866. this._displayTeleportationTarget();
  82867. this._haloCenter.copyFrom(hit.pickedPoint);
  82868. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  82869. }
  82870. var pickNormal = hit.getNormal(true, false);
  82871. if (pickNormal) {
  82872. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82873. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82874. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  82875. }
  82876. this._teleportationTarget.position.y += 0.1;
  82877. }
  82878. };
  82879. VRExperienceHelper.prototype._teleportCamera = function (location) {
  82880. var _this = this;
  82881. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82882. return;
  82883. }
  82884. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  82885. // offset of the headset from the anchor.
  82886. if (this.webVRCamera.leftCamera) {
  82887. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  82888. this._workingVector.subtractInPlace(this.webVRCamera.position);
  82889. location.subtractToRef(this._workingVector, this._workingVector);
  82890. }
  82891. else {
  82892. this._workingVector.copyFrom(location);
  82893. }
  82894. // Add height to account for user's height offset
  82895. if (this.isInVRMode) {
  82896. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  82897. }
  82898. else {
  82899. this._workingVector.y += this._defaultHeight;
  82900. }
  82901. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  82902. // Create animation from the camera's position to the new location
  82903. this.currentVRCamera.animations = [];
  82904. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82905. var animationCameraTeleportationKeys = [{
  82906. frame: 0,
  82907. value: this.currentVRCamera.position
  82908. },
  82909. {
  82910. frame: 11,
  82911. value: this._workingVector
  82912. }
  82913. ];
  82914. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  82915. animationCameraTeleportation.setEasingFunction(this._circleEase);
  82916. this.currentVRCamera.animations.push(animationCameraTeleportation);
  82917. this._postProcessMove.animations = [];
  82918. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82919. var vignetteWeightKeys = [];
  82920. vignetteWeightKeys.push({
  82921. frame: 0,
  82922. value: 0
  82923. });
  82924. vignetteWeightKeys.push({
  82925. frame: 5,
  82926. value: 8
  82927. });
  82928. vignetteWeightKeys.push({
  82929. frame: 11,
  82930. value: 0
  82931. });
  82932. animationPP.setKeys(vignetteWeightKeys);
  82933. this._postProcessMove.animations.push(animationPP);
  82934. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  82935. var vignetteStretchKeys = [];
  82936. vignetteStretchKeys.push({
  82937. frame: 0,
  82938. value: 0
  82939. });
  82940. vignetteStretchKeys.push({
  82941. frame: 5,
  82942. value: 10
  82943. });
  82944. vignetteStretchKeys.push({
  82945. frame: 11,
  82946. value: 0
  82947. });
  82948. animationPP2.setKeys(vignetteStretchKeys);
  82949. this._postProcessMove.animations.push(animationPP2);
  82950. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  82951. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  82952. this._webVRCamera.attachPostProcess(this._postProcessMove);
  82953. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  82954. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  82955. });
  82956. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  82957. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  82958. });
  82959. this._hideTeleportationTarget();
  82960. };
  82961. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  82962. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  82963. return;
  82964. }
  82965. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  82966. // Moving the gazeTracker on the mesh face targetted
  82967. if (hit && hit.pickedPoint) {
  82968. if (this._displayGaze) {
  82969. var multiplier = 1;
  82970. gazer._gazeTracker.isVisible = true;
  82971. if (gazer._isActionableMesh) {
  82972. multiplier = 3;
  82973. }
  82974. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  82975. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  82976. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  82977. var pickNormal = hit.getNormal();
  82978. // To avoid z-fighting
  82979. var deltaFighting = 0.002;
  82980. if (pickNormal) {
  82981. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  82982. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  82983. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  82984. }
  82985. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  82986. if (gazer._gazeTracker.position.x < 0) {
  82987. gazer._gazeTracker.position.x += deltaFighting;
  82988. }
  82989. else {
  82990. gazer._gazeTracker.position.x -= deltaFighting;
  82991. }
  82992. if (gazer._gazeTracker.position.y < 0) {
  82993. gazer._gazeTracker.position.y += deltaFighting;
  82994. }
  82995. else {
  82996. gazer._gazeTracker.position.y -= deltaFighting;
  82997. }
  82998. if (gazer._gazeTracker.position.z < 0) {
  82999. gazer._gazeTracker.position.z += deltaFighting;
  83000. }
  83001. else {
  83002. gazer._gazeTracker.position.z -= deltaFighting;
  83003. }
  83004. }
  83005. // Changing the size of the laser pointer based on the distance from the targetted point
  83006. gazer._updatePointerDistance(hit.distance);
  83007. }
  83008. else {
  83009. gazer._gazeTracker.isVisible = false;
  83010. }
  83011. if (hit && hit.pickedMesh) {
  83012. gazer._currentHit = hit;
  83013. if (gazer._pointerDownOnMeshAsked) {
  83014. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  83015. }
  83016. // The object selected is the floor, we're in a teleportation scenario
  83017. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  83018. // Moving the teleportation area to this targetted point
  83019. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  83020. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  83021. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83022. }
  83023. gazer._currentMeshSelected = null;
  83024. if (gazer._teleportationRequestInitiated) {
  83025. this._moveTeleportationSelectorTo(hit, gazer);
  83026. }
  83027. return;
  83028. }
  83029. // If not, we're in a selection scenario
  83030. //this._teleportationAllowed = false;
  83031. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  83032. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  83033. this.onNewMeshPicked.notifyObservers(hit);
  83034. gazer._currentMeshSelected = hit.pickedMesh;
  83035. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  83036. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  83037. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  83038. gazer._isActionableMesh = true;
  83039. }
  83040. else {
  83041. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83042. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83043. gazer._isActionableMesh = false;
  83044. }
  83045. try {
  83046. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  83047. }
  83048. catch (err) {
  83049. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  83050. }
  83051. }
  83052. else {
  83053. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83054. gazer._currentMeshSelected = null;
  83055. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83056. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83057. }
  83058. }
  83059. }
  83060. else {
  83061. gazer._currentHit = null;
  83062. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83063. gazer._currentMeshSelected = null;
  83064. //this._teleportationAllowed = false;
  83065. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83066. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83067. }
  83068. };
  83069. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  83070. if (mesh) {
  83071. this.onSelectedMeshUnselected.notifyObservers(mesh);
  83072. }
  83073. };
  83074. /**
  83075. * Sets the color of the laser ray from the vr controllers.
  83076. * @param color new color for the ray.
  83077. */
  83078. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  83079. if (this.leftController) {
  83080. this.leftController._setLaserPointerColor(color);
  83081. }
  83082. if (this.rightController) {
  83083. this.rightController._setLaserPointerColor(color);
  83084. }
  83085. };
  83086. /**
  83087. * Sets the color of the ray from the vr headsets gaze.
  83088. * @param color new color for the ray.
  83089. */
  83090. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  83091. if (!this._cameraGazer._gazeTracker.material) {
  83092. return;
  83093. }
  83094. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  83095. if (this.leftController) {
  83096. this.leftController._gazeTracker.material.emissiveColor = color;
  83097. }
  83098. if (this.rightController) {
  83099. this.rightController._gazeTracker.material.emissiveColor = color;
  83100. }
  83101. };
  83102. /**
  83103. * Exits VR and disposes of the vr experience helper
  83104. */
  83105. VRExperienceHelper.prototype.dispose = function () {
  83106. if (this.isInVRMode) {
  83107. this.exitVR();
  83108. }
  83109. if (this._postProcessMove) {
  83110. this._postProcessMove.dispose();
  83111. }
  83112. if (this._webVRCamera) {
  83113. this._webVRCamera.dispose();
  83114. }
  83115. if (this._vrDeviceOrientationCamera) {
  83116. this._vrDeviceOrientationCamera.dispose();
  83117. }
  83118. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  83119. document.body.removeChild(this._btnVR);
  83120. }
  83121. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  83122. this._deviceOrientationCamera.dispose();
  83123. }
  83124. if (this._cameraGazer) {
  83125. this._cameraGazer.dispose();
  83126. }
  83127. if (this.leftController) {
  83128. this.leftController.dispose();
  83129. }
  83130. if (this.rightController) {
  83131. this.rightController.dispose();
  83132. }
  83133. if (this._teleportationTarget) {
  83134. this._teleportationTarget.dispose();
  83135. }
  83136. this._floorMeshesCollection = [];
  83137. document.removeEventListener("keydown", this._onKeyDown);
  83138. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83139. window.removeEventListener("resize", this._onResize);
  83140. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  83141. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  83142. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  83143. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  83144. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  83145. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  83146. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  83147. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83148. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  83149. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  83150. this._scene.unregisterBeforeRender(this.beforeRender);
  83151. };
  83152. /**
  83153. * Gets the name of the VRExperienceHelper class
  83154. * @returns "VRExperienceHelper"
  83155. */
  83156. VRExperienceHelper.prototype.getClassName = function () {
  83157. return "VRExperienceHelper";
  83158. };
  83159. return VRExperienceHelper;
  83160. }());
  83161. BABYLON.VRExperienceHelper = VRExperienceHelper;
  83162. })(BABYLON || (BABYLON = {}));
  83163. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  83164. "use strict";
  83165. // Mainly based on these 2 articles :
  83166. // 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
  83167. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  83168. var BABYLON;
  83169. (function (BABYLON) {
  83170. var JoystickAxis;
  83171. (function (JoystickAxis) {
  83172. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  83173. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  83174. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  83175. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  83176. var VirtualJoystick = /** @class */ (function () {
  83177. function VirtualJoystick(leftJoystick) {
  83178. var _this = this;
  83179. if (leftJoystick) {
  83180. this._leftJoystick = true;
  83181. }
  83182. else {
  83183. this._leftJoystick = false;
  83184. }
  83185. VirtualJoystick._globalJoystickIndex++;
  83186. // By default left & right arrow keys are moving the X
  83187. // and up & down keys are moving the Y
  83188. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83189. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83190. this.reverseLeftRight = false;
  83191. this.reverseUpDown = false;
  83192. // collections of pointers
  83193. this._touches = new BABYLON.StringDictionary();
  83194. this.deltaPosition = BABYLON.Vector3.Zero();
  83195. this._joystickSensibility = 25;
  83196. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83197. this._onResize = function (evt) {
  83198. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83199. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83200. if (VirtualJoystick.vjCanvas) {
  83201. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83202. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83203. }
  83204. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83205. };
  83206. // injecting a canvas element on top of the canvas 3D game
  83207. if (!VirtualJoystick.vjCanvas) {
  83208. window.addEventListener("resize", this._onResize, false);
  83209. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83210. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83211. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83212. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83213. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83214. VirtualJoystick.vjCanvas.style.width = "100%";
  83215. VirtualJoystick.vjCanvas.style.height = "100%";
  83216. VirtualJoystick.vjCanvas.style.position = "absolute";
  83217. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83218. VirtualJoystick.vjCanvas.style.top = "0px";
  83219. VirtualJoystick.vjCanvas.style.left = "0px";
  83220. VirtualJoystick.vjCanvas.style.zIndex = "5";
  83221. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  83222. // Support for jQuery PEP polyfill
  83223. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  83224. var context = VirtualJoystick.vjCanvas.getContext('2d');
  83225. if (!context) {
  83226. throw new Error("Unable to create canvas for virtual joystick");
  83227. }
  83228. VirtualJoystick.vjCanvasContext = context;
  83229. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  83230. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83231. document.body.appendChild(VirtualJoystick.vjCanvas);
  83232. }
  83233. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  83234. this.pressed = false;
  83235. // default joystick color
  83236. this._joystickColor = "cyan";
  83237. this._joystickPointerID = -1;
  83238. // current joystick position
  83239. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  83240. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  83241. // origin joystick position
  83242. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  83243. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  83244. this._onPointerDownHandlerRef = function (evt) {
  83245. _this._onPointerDown(evt);
  83246. };
  83247. this._onPointerMoveHandlerRef = function (evt) {
  83248. _this._onPointerMove(evt);
  83249. };
  83250. this._onPointerUpHandlerRef = function (evt) {
  83251. _this._onPointerUp(evt);
  83252. };
  83253. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  83254. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  83255. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  83256. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  83257. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  83258. evt.preventDefault(); // Disables system menu
  83259. }, false);
  83260. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83261. }
  83262. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  83263. this._joystickSensibility = newJoystickSensibility;
  83264. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83265. };
  83266. VirtualJoystick.prototype._onPointerDown = function (e) {
  83267. var positionOnScreenCondition;
  83268. e.preventDefault();
  83269. if (this._leftJoystick === true) {
  83270. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  83271. }
  83272. else {
  83273. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  83274. }
  83275. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  83276. // First contact will be dedicated to the virtual joystick
  83277. this._joystickPointerID = e.pointerId;
  83278. this._joystickPointerStartPos.x = e.clientX;
  83279. this._joystickPointerStartPos.y = e.clientY;
  83280. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  83281. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  83282. this._deltaJoystickVector.x = 0;
  83283. this._deltaJoystickVector.y = 0;
  83284. this.pressed = true;
  83285. this._touches.add(e.pointerId.toString(), e);
  83286. }
  83287. else {
  83288. // You can only trigger the action buttons with a joystick declared
  83289. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  83290. this._action();
  83291. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  83292. }
  83293. }
  83294. };
  83295. VirtualJoystick.prototype._onPointerMove = function (e) {
  83296. // If the current pointer is the one associated to the joystick (first touch contact)
  83297. if (this._joystickPointerID == e.pointerId) {
  83298. this._joystickPointerPos.x = e.clientX;
  83299. this._joystickPointerPos.y = e.clientY;
  83300. this._deltaJoystickVector = this._joystickPointerPos.clone();
  83301. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  83302. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  83303. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  83304. switch (this._axisTargetedByLeftAndRight) {
  83305. case JoystickAxis.X:
  83306. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  83307. break;
  83308. case JoystickAxis.Y:
  83309. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  83310. break;
  83311. case JoystickAxis.Z:
  83312. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  83313. break;
  83314. }
  83315. var directionUpDown = this.reverseUpDown ? 1 : -1;
  83316. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  83317. switch (this._axisTargetedByUpAndDown) {
  83318. case JoystickAxis.X:
  83319. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  83320. break;
  83321. case JoystickAxis.Y:
  83322. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  83323. break;
  83324. case JoystickAxis.Z:
  83325. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  83326. break;
  83327. }
  83328. }
  83329. else {
  83330. var data = this._touches.get(e.pointerId.toString());
  83331. if (data) {
  83332. data.x = e.clientX;
  83333. data.y = e.clientY;
  83334. }
  83335. }
  83336. };
  83337. VirtualJoystick.prototype._onPointerUp = function (e) {
  83338. if (this._joystickPointerID == e.pointerId) {
  83339. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  83340. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  83341. this._joystickPointerID = -1;
  83342. this.pressed = false;
  83343. }
  83344. else {
  83345. var touch = this._touches.get(e.pointerId.toString());
  83346. if (touch) {
  83347. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83348. }
  83349. }
  83350. this._deltaJoystickVector.x = 0;
  83351. this._deltaJoystickVector.y = 0;
  83352. this._touches.remove(e.pointerId.toString());
  83353. };
  83354. /**
  83355. * Change the color of the virtual joystick
  83356. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  83357. */
  83358. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  83359. this._joystickColor = newColor;
  83360. };
  83361. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  83362. this._action = action;
  83363. };
  83364. // Define which axis you'd like to control for left & right
  83365. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  83366. switch (axis) {
  83367. case JoystickAxis.X:
  83368. case JoystickAxis.Y:
  83369. case JoystickAxis.Z:
  83370. this._axisTargetedByLeftAndRight = axis;
  83371. break;
  83372. default:
  83373. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83374. break;
  83375. }
  83376. };
  83377. // Define which axis you'd like to control for up & down
  83378. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  83379. switch (axis) {
  83380. case JoystickAxis.X:
  83381. case JoystickAxis.Y:
  83382. case JoystickAxis.Z:
  83383. this._axisTargetedByUpAndDown = axis;
  83384. break;
  83385. default:
  83386. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83387. break;
  83388. }
  83389. };
  83390. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  83391. var _this = this;
  83392. if (this.pressed) {
  83393. this._touches.forEach(function (key, touch) {
  83394. if (touch.pointerId === _this._joystickPointerID) {
  83395. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  83396. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  83397. VirtualJoystick.vjCanvasContext.beginPath();
  83398. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83399. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83400. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  83401. VirtualJoystick.vjCanvasContext.stroke();
  83402. VirtualJoystick.vjCanvasContext.closePath();
  83403. VirtualJoystick.vjCanvasContext.beginPath();
  83404. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83405. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83406. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  83407. VirtualJoystick.vjCanvasContext.stroke();
  83408. VirtualJoystick.vjCanvasContext.closePath();
  83409. VirtualJoystick.vjCanvasContext.beginPath();
  83410. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  83411. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  83412. VirtualJoystick.vjCanvasContext.stroke();
  83413. VirtualJoystick.vjCanvasContext.closePath();
  83414. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  83415. }
  83416. else {
  83417. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  83418. VirtualJoystick.vjCanvasContext.beginPath();
  83419. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  83420. VirtualJoystick.vjCanvasContext.beginPath();
  83421. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  83422. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  83423. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  83424. VirtualJoystick.vjCanvasContext.stroke();
  83425. VirtualJoystick.vjCanvasContext.closePath();
  83426. touch.prevX = touch.x;
  83427. touch.prevY = touch.y;
  83428. }
  83429. ;
  83430. });
  83431. }
  83432. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83433. };
  83434. VirtualJoystick.prototype.releaseCanvas = function () {
  83435. if (VirtualJoystick.vjCanvas) {
  83436. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  83437. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  83438. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  83439. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  83440. window.removeEventListener("resize", this._onResize);
  83441. document.body.removeChild(VirtualJoystick.vjCanvas);
  83442. VirtualJoystick.vjCanvas = null;
  83443. }
  83444. };
  83445. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  83446. VirtualJoystick._globalJoystickIndex = 0;
  83447. return VirtualJoystick;
  83448. }());
  83449. BABYLON.VirtualJoystick = VirtualJoystick;
  83450. })(BABYLON || (BABYLON = {}));
  83451. //# sourceMappingURL=babylon.virtualJoystick.js.map
  83452. "use strict";
  83453. var BABYLON;
  83454. (function (BABYLON) {
  83455. // We're mainly based on the logic defined into the FreeCamera code
  83456. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  83457. __extends(VirtualJoysticksCamera, _super);
  83458. function VirtualJoysticksCamera(name, position, scene) {
  83459. var _this = _super.call(this, name, position, scene) || this;
  83460. _this.inputs.addVirtualJoystick();
  83461. return _this;
  83462. }
  83463. VirtualJoysticksCamera.prototype.getClassName = function () {
  83464. return "VirtualJoysticksCamera";
  83465. };
  83466. return VirtualJoysticksCamera;
  83467. }(BABYLON.FreeCamera));
  83468. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  83469. })(BABYLON || (BABYLON = {}));
  83470. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  83471. "use strict";
  83472. var BABYLON;
  83473. (function (BABYLON) {
  83474. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  83475. function FreeCameraVirtualJoystickInput() {
  83476. }
  83477. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  83478. return this._leftjoystick;
  83479. };
  83480. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  83481. return this._rightjoystick;
  83482. };
  83483. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  83484. if (this._leftjoystick) {
  83485. var camera = this.camera;
  83486. var speed = camera._computeLocalCameraSpeed() * 50;
  83487. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  83488. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  83489. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  83490. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  83491. if (!this._leftjoystick.pressed) {
  83492. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  83493. }
  83494. if (!this._rightjoystick.pressed) {
  83495. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  83496. }
  83497. }
  83498. };
  83499. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  83500. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  83501. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  83502. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  83503. this._leftjoystick.setJoystickSensibility(0.15);
  83504. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  83505. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  83506. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  83507. this._rightjoystick.reverseUpDown = true;
  83508. this._rightjoystick.setJoystickSensibility(0.05);
  83509. this._rightjoystick.setJoystickColor("yellow");
  83510. };
  83511. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  83512. this._leftjoystick.releaseCanvas();
  83513. this._rightjoystick.releaseCanvas();
  83514. };
  83515. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  83516. return "FreeCameraVirtualJoystickInput";
  83517. };
  83518. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  83519. return "virtualJoystick";
  83520. };
  83521. return FreeCameraVirtualJoystickInput;
  83522. }());
  83523. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  83524. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  83525. })(BABYLON || (BABYLON = {}));
  83526. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  83527. "use strict";
  83528. var BABYLON;
  83529. (function (BABYLON) {
  83530. var SimplificationSettings = /** @class */ (function () {
  83531. function SimplificationSettings(quality, distance, optimizeMesh) {
  83532. this.quality = quality;
  83533. this.distance = distance;
  83534. this.optimizeMesh = optimizeMesh;
  83535. }
  83536. return SimplificationSettings;
  83537. }());
  83538. BABYLON.SimplificationSettings = SimplificationSettings;
  83539. var SimplificationQueue = /** @class */ (function () {
  83540. function SimplificationQueue() {
  83541. this.running = false;
  83542. this._simplificationArray = [];
  83543. }
  83544. SimplificationQueue.prototype.addTask = function (task) {
  83545. this._simplificationArray.push(task);
  83546. };
  83547. SimplificationQueue.prototype.executeNext = function () {
  83548. var task = this._simplificationArray.pop();
  83549. if (task) {
  83550. this.running = true;
  83551. this.runSimplification(task);
  83552. }
  83553. else {
  83554. this.running = false;
  83555. }
  83556. };
  83557. SimplificationQueue.prototype.runSimplification = function (task) {
  83558. var _this = this;
  83559. if (task.parallelProcessing) {
  83560. //parallel simplifier
  83561. task.settings.forEach(function (setting) {
  83562. var simplifier = _this.getSimplifier(task);
  83563. simplifier.simplify(setting, function (newMesh) {
  83564. task.mesh.addLODLevel(setting.distance, newMesh);
  83565. newMesh.isVisible = true;
  83566. //check if it is the last
  83567. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  83568. //all done, run the success callback.
  83569. task.successCallback();
  83570. }
  83571. _this.executeNext();
  83572. });
  83573. });
  83574. }
  83575. else {
  83576. //single simplifier.
  83577. var simplifier = this.getSimplifier(task);
  83578. var runDecimation = function (setting, callback) {
  83579. simplifier.simplify(setting, function (newMesh) {
  83580. task.mesh.addLODLevel(setting.distance, newMesh);
  83581. newMesh.isVisible = true;
  83582. //run the next quality level
  83583. callback();
  83584. });
  83585. };
  83586. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  83587. runDecimation(task.settings[loop.index], function () {
  83588. loop.executeNext();
  83589. });
  83590. }, function () {
  83591. //execution ended, run the success callback.
  83592. if (task.successCallback) {
  83593. task.successCallback();
  83594. }
  83595. _this.executeNext();
  83596. });
  83597. }
  83598. };
  83599. SimplificationQueue.prototype.getSimplifier = function (task) {
  83600. switch (task.simplificationType) {
  83601. case SimplificationType.QUADRATIC:
  83602. default:
  83603. return new QuadraticErrorSimplification(task.mesh);
  83604. }
  83605. };
  83606. return SimplificationQueue;
  83607. }());
  83608. BABYLON.SimplificationQueue = SimplificationQueue;
  83609. /**
  83610. * The implemented types of simplification.
  83611. * At the moment only Quadratic Error Decimation is implemented.
  83612. */
  83613. var SimplificationType;
  83614. (function (SimplificationType) {
  83615. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  83616. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  83617. var DecimationTriangle = /** @class */ (function () {
  83618. function DecimationTriangle(vertices) {
  83619. this.vertices = vertices;
  83620. this.error = new Array(4);
  83621. this.deleted = false;
  83622. this.isDirty = false;
  83623. this.deletePending = false;
  83624. this.borderFactor = 0;
  83625. }
  83626. return DecimationTriangle;
  83627. }());
  83628. BABYLON.DecimationTriangle = DecimationTriangle;
  83629. var DecimationVertex = /** @class */ (function () {
  83630. function DecimationVertex(position, id) {
  83631. this.position = position;
  83632. this.id = id;
  83633. this.isBorder = true;
  83634. this.q = new QuadraticMatrix();
  83635. this.triangleCount = 0;
  83636. this.triangleStart = 0;
  83637. this.originalOffsets = [];
  83638. }
  83639. DecimationVertex.prototype.updatePosition = function (newPosition) {
  83640. this.position.copyFrom(newPosition);
  83641. };
  83642. return DecimationVertex;
  83643. }());
  83644. BABYLON.DecimationVertex = DecimationVertex;
  83645. var QuadraticMatrix = /** @class */ (function () {
  83646. function QuadraticMatrix(data) {
  83647. this.data = new Array(10);
  83648. for (var i = 0; i < 10; ++i) {
  83649. if (data && data[i]) {
  83650. this.data[i] = data[i];
  83651. }
  83652. else {
  83653. this.data[i] = 0;
  83654. }
  83655. }
  83656. }
  83657. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  83658. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  83659. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  83660. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  83661. return det;
  83662. };
  83663. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  83664. for (var i = 0; i < 10; ++i) {
  83665. this.data[i] += matrix.data[i];
  83666. }
  83667. };
  83668. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  83669. for (var i = 0; i < 10; ++i) {
  83670. this.data[i] += data[i];
  83671. }
  83672. };
  83673. QuadraticMatrix.prototype.add = function (matrix) {
  83674. var m = new QuadraticMatrix();
  83675. for (var i = 0; i < 10; ++i) {
  83676. m.data[i] = this.data[i] + matrix.data[i];
  83677. }
  83678. return m;
  83679. };
  83680. QuadraticMatrix.FromData = function (a, b, c, d) {
  83681. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  83682. };
  83683. //returning an array to avoid garbage collection
  83684. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  83685. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  83686. };
  83687. return QuadraticMatrix;
  83688. }());
  83689. BABYLON.QuadraticMatrix = QuadraticMatrix;
  83690. var Reference = /** @class */ (function () {
  83691. function Reference(vertexId, triangleId) {
  83692. this.vertexId = vertexId;
  83693. this.triangleId = triangleId;
  83694. }
  83695. return Reference;
  83696. }());
  83697. BABYLON.Reference = Reference;
  83698. /**
  83699. * An implementation of the Quadratic Error simplification algorithm.
  83700. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  83701. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  83702. * @author RaananW
  83703. */
  83704. var QuadraticErrorSimplification = /** @class */ (function () {
  83705. function QuadraticErrorSimplification(_mesh) {
  83706. this._mesh = _mesh;
  83707. this.syncIterations = 5000;
  83708. this.aggressiveness = 7;
  83709. this.decimationIterations = 100;
  83710. this.boundingBoxEpsilon = BABYLON.Epsilon;
  83711. }
  83712. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  83713. var _this = this;
  83714. this.initDecimatedMesh();
  83715. //iterating through the submeshes array, one after the other.
  83716. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  83717. _this.initWithMesh(loop.index, function () {
  83718. _this.runDecimation(settings, loop.index, function () {
  83719. loop.executeNext();
  83720. });
  83721. }, settings.optimizeMesh);
  83722. }, function () {
  83723. setTimeout(function () {
  83724. successCallback(_this._reconstructedMesh);
  83725. }, 0);
  83726. });
  83727. };
  83728. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  83729. var _this = this;
  83730. var targetCount = ~~(this.triangles.length * settings.quality);
  83731. var deletedTriangles = 0;
  83732. var triangleCount = this.triangles.length;
  83733. var iterationFunction = function (iteration, callback) {
  83734. setTimeout(function () {
  83735. if (iteration % 5 === 0) {
  83736. _this.updateMesh(iteration === 0);
  83737. }
  83738. for (var i = 0; i < _this.triangles.length; ++i) {
  83739. _this.triangles[i].isDirty = false;
  83740. }
  83741. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  83742. var trianglesIterator = function (i) {
  83743. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  83744. var t = _this.triangles[tIdx];
  83745. if (!t)
  83746. return;
  83747. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  83748. return;
  83749. }
  83750. for (var j = 0; j < 3; ++j) {
  83751. if (t.error[j] < threshold) {
  83752. var deleted0 = [];
  83753. var deleted1 = [];
  83754. var v0 = t.vertices[j];
  83755. var v1 = t.vertices[(j + 1) % 3];
  83756. if (v0.isBorder || v1.isBorder)
  83757. continue;
  83758. var p = BABYLON.Vector3.Zero();
  83759. var n = BABYLON.Vector3.Zero();
  83760. var uv = BABYLON.Vector2.Zero();
  83761. var color = new BABYLON.Color4(0, 0, 0, 1);
  83762. _this.calculateError(v0, v1, p, n, uv, color);
  83763. var delTr = new Array();
  83764. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  83765. continue;
  83766. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  83767. continue;
  83768. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  83769. continue;
  83770. var uniqueArray = new Array();
  83771. delTr.forEach(function (deletedT) {
  83772. if (uniqueArray.indexOf(deletedT) === -1) {
  83773. deletedT.deletePending = true;
  83774. uniqueArray.push(deletedT);
  83775. }
  83776. });
  83777. if (uniqueArray.length % 2 !== 0) {
  83778. continue;
  83779. }
  83780. v0.q = v1.q.add(v0.q);
  83781. v0.updatePosition(p);
  83782. var tStart = _this.references.length;
  83783. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  83784. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  83785. var tCount = _this.references.length - tStart;
  83786. if (tCount <= v0.triangleCount) {
  83787. if (tCount) {
  83788. for (var c = 0; c < tCount; c++) {
  83789. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  83790. }
  83791. }
  83792. }
  83793. else {
  83794. v0.triangleStart = tStart;
  83795. }
  83796. v0.triangleCount = tCount;
  83797. break;
  83798. }
  83799. }
  83800. };
  83801. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  83802. }, 0);
  83803. };
  83804. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  83805. if (triangleCount - deletedTriangles <= targetCount)
  83806. loop.breakLoop();
  83807. else {
  83808. iterationFunction(loop.index, function () {
  83809. loop.executeNext();
  83810. });
  83811. }
  83812. }, function () {
  83813. setTimeout(function () {
  83814. //reconstruct this part of the mesh
  83815. _this.reconstructMesh(submeshIndex);
  83816. successCallback();
  83817. }, 0);
  83818. });
  83819. };
  83820. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  83821. var _this = this;
  83822. this.vertices = [];
  83823. this.triangles = [];
  83824. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83825. var indices = this._mesh.getIndices();
  83826. var submesh = this._mesh.subMeshes[submeshIndex];
  83827. var findInVertices = function (positionToSearch) {
  83828. if (optimizeMesh) {
  83829. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  83830. if (_this.vertices[ii].position.equals(positionToSearch)) {
  83831. return _this.vertices[ii];
  83832. }
  83833. }
  83834. }
  83835. return null;
  83836. };
  83837. var vertexReferences = [];
  83838. var vertexInit = function (i) {
  83839. if (!positionData) {
  83840. return;
  83841. }
  83842. var offset = i + submesh.verticesStart;
  83843. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  83844. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  83845. vertex.originalOffsets.push(offset);
  83846. if (vertex.id === _this.vertices.length) {
  83847. _this.vertices.push(vertex);
  83848. }
  83849. vertexReferences.push(vertex.id);
  83850. };
  83851. //var totalVertices = mesh.getTotalVertices();
  83852. var totalVertices = submesh.verticesCount;
  83853. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  83854. var indicesInit = function (i) {
  83855. if (!indices) {
  83856. return;
  83857. }
  83858. var offset = (submesh.indexStart / 3) + i;
  83859. var pos = (offset * 3);
  83860. var i0 = indices[pos + 0];
  83861. var i1 = indices[pos + 1];
  83862. var i2 = indices[pos + 2];
  83863. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  83864. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  83865. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  83866. var triangle = new DecimationTriangle([v0, v1, v2]);
  83867. triangle.originalOffset = pos;
  83868. _this.triangles.push(triangle);
  83869. };
  83870. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  83871. _this.init(callback);
  83872. });
  83873. });
  83874. };
  83875. QuadraticErrorSimplification.prototype.init = function (callback) {
  83876. var _this = this;
  83877. var triangleInit1 = function (i) {
  83878. var t = _this.triangles[i];
  83879. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  83880. for (var j = 0; j < 3; j++) {
  83881. 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))));
  83882. }
  83883. };
  83884. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  83885. var triangleInit2 = function (i) {
  83886. var t = _this.triangles[i];
  83887. for (var j = 0; j < 3; ++j) {
  83888. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  83889. }
  83890. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  83891. };
  83892. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  83893. callback();
  83894. });
  83895. });
  83896. };
  83897. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  83898. var newTriangles = [];
  83899. var i;
  83900. for (i = 0; i < this.vertices.length; ++i) {
  83901. this.vertices[i].triangleCount = 0;
  83902. }
  83903. var t;
  83904. var j;
  83905. for (i = 0; i < this.triangles.length; ++i) {
  83906. if (!this.triangles[i].deleted) {
  83907. t = this.triangles[i];
  83908. for (j = 0; j < 3; ++j) {
  83909. t.vertices[j].triangleCount = 1;
  83910. }
  83911. newTriangles.push(t);
  83912. }
  83913. }
  83914. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  83915. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  83916. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  83917. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  83918. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  83919. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83920. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  83921. var vertexCount = 0;
  83922. for (i = 0; i < this.vertices.length; ++i) {
  83923. var vertex = this.vertices[i];
  83924. vertex.id = vertexCount;
  83925. if (vertex.triangleCount) {
  83926. vertex.originalOffsets.forEach(function (originalOffset) {
  83927. if (!normalData) {
  83928. return;
  83929. }
  83930. newPositionData.push(vertex.position.x);
  83931. newPositionData.push(vertex.position.y);
  83932. newPositionData.push(vertex.position.z);
  83933. newNormalData.push(normalData[originalOffset * 3]);
  83934. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  83935. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  83936. if (uvs && uvs.length) {
  83937. newUVsData.push(uvs[(originalOffset * 2)]);
  83938. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  83939. }
  83940. else if (colorsData && colorsData.length) {
  83941. newColorsData.push(colorsData[(originalOffset * 4)]);
  83942. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  83943. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  83944. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  83945. }
  83946. ++vertexCount;
  83947. });
  83948. }
  83949. }
  83950. var startingIndex = this._reconstructedMesh.getTotalIndices();
  83951. var startingVertex = this._reconstructedMesh.getTotalVertices();
  83952. var submeshesArray = this._reconstructedMesh.subMeshes;
  83953. this._reconstructedMesh.subMeshes = [];
  83954. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  83955. var originalIndices = this._mesh.getIndices();
  83956. for (i = 0; i < newTriangles.length; ++i) {
  83957. t = newTriangles[i]; //now get the new referencing point for each vertex
  83958. [0, 1, 2].forEach(function (idx) {
  83959. var id = originalIndices[t.originalOffset + idx];
  83960. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  83961. if (offset < 0)
  83962. offset = 0;
  83963. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  83964. });
  83965. }
  83966. //overwriting the old vertex buffers and indices.
  83967. this._reconstructedMesh.setIndices(newIndicesArray);
  83968. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  83969. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  83970. if (newUVsData.length > 0)
  83971. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  83972. if (newColorsData.length > 0)
  83973. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  83974. //create submesh
  83975. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  83976. if (submeshIndex > 0) {
  83977. this._reconstructedMesh.subMeshes = [];
  83978. submeshesArray.forEach(function (submesh) {
  83979. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  83980. });
  83981. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  83982. }
  83983. };
  83984. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  83985. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  83986. this._reconstructedMesh.material = this._mesh.material;
  83987. this._reconstructedMesh.parent = this._mesh.parent;
  83988. this._reconstructedMesh.isVisible = false;
  83989. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  83990. };
  83991. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  83992. for (var i = 0; i < vertex1.triangleCount; ++i) {
  83993. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  83994. if (t.deleted)
  83995. continue;
  83996. var s = this.references[vertex1.triangleStart + i].vertexId;
  83997. var v1 = t.vertices[(s + 1) % 3];
  83998. var v2 = t.vertices[(s + 2) % 3];
  83999. if ((v1 === vertex2 || v2 === vertex2)) {
  84000. deletedArray[i] = true;
  84001. delTr.push(t);
  84002. continue;
  84003. }
  84004. var d1 = v1.position.subtract(point);
  84005. d1 = d1.normalize();
  84006. var d2 = v2.position.subtract(point);
  84007. d2 = d2.normalize();
  84008. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  84009. return true;
  84010. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  84011. deletedArray[i] = false;
  84012. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  84013. return true;
  84014. }
  84015. return false;
  84016. };
  84017. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  84018. var newDeleted = deletedTriangles;
  84019. for (var i = 0; i < vertex.triangleCount; ++i) {
  84020. var ref = this.references[vertex.triangleStart + i];
  84021. var t = this.triangles[ref.triangleId];
  84022. if (t.deleted)
  84023. continue;
  84024. if (deletedArray[i] && t.deletePending) {
  84025. t.deleted = true;
  84026. newDeleted++;
  84027. continue;
  84028. }
  84029. t.vertices[ref.vertexId] = origVertex;
  84030. t.isDirty = true;
  84031. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  84032. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  84033. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  84034. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84035. this.references.push(ref);
  84036. }
  84037. return newDeleted;
  84038. };
  84039. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  84040. for (var i = 0; i < this.vertices.length; ++i) {
  84041. var vCount = [];
  84042. var vId = [];
  84043. var v = this.vertices[i];
  84044. var j;
  84045. for (j = 0; j < v.triangleCount; ++j) {
  84046. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  84047. for (var ii = 0; ii < 3; ii++) {
  84048. var ofs = 0;
  84049. var vv = triangle.vertices[ii];
  84050. while (ofs < vCount.length) {
  84051. if (vId[ofs] === vv.id)
  84052. break;
  84053. ++ofs;
  84054. }
  84055. if (ofs === vCount.length) {
  84056. vCount.push(1);
  84057. vId.push(vv.id);
  84058. }
  84059. else {
  84060. vCount[ofs]++;
  84061. }
  84062. }
  84063. }
  84064. for (j = 0; j < vCount.length; ++j) {
  84065. if (vCount[j] === 1) {
  84066. this.vertices[vId[j]].isBorder = true;
  84067. }
  84068. else {
  84069. this.vertices[vId[j]].isBorder = false;
  84070. }
  84071. }
  84072. }
  84073. };
  84074. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  84075. if (identifyBorders === void 0) { identifyBorders = false; }
  84076. var i;
  84077. if (!identifyBorders) {
  84078. var newTrianglesVector = [];
  84079. for (i = 0; i < this.triangles.length; ++i) {
  84080. if (!this.triangles[i].deleted) {
  84081. newTrianglesVector.push(this.triangles[i]);
  84082. }
  84083. }
  84084. this.triangles = newTrianglesVector;
  84085. }
  84086. for (i = 0; i < this.vertices.length; ++i) {
  84087. this.vertices[i].triangleCount = 0;
  84088. this.vertices[i].triangleStart = 0;
  84089. }
  84090. var t;
  84091. var j;
  84092. var v;
  84093. for (i = 0; i < this.triangles.length; ++i) {
  84094. t = this.triangles[i];
  84095. for (j = 0; j < 3; ++j) {
  84096. v = t.vertices[j];
  84097. v.triangleCount++;
  84098. }
  84099. }
  84100. var tStart = 0;
  84101. for (i = 0; i < this.vertices.length; ++i) {
  84102. this.vertices[i].triangleStart = tStart;
  84103. tStart += this.vertices[i].triangleCount;
  84104. this.vertices[i].triangleCount = 0;
  84105. }
  84106. var newReferences = new Array(this.triangles.length * 3);
  84107. for (i = 0; i < this.triangles.length; ++i) {
  84108. t = this.triangles[i];
  84109. for (j = 0; j < 3; ++j) {
  84110. v = t.vertices[j];
  84111. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  84112. v.triangleCount++;
  84113. }
  84114. }
  84115. this.references = newReferences;
  84116. if (identifyBorders) {
  84117. this.identifyBorder();
  84118. }
  84119. };
  84120. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  84121. var x = point.x;
  84122. var y = point.y;
  84123. var z = point.z;
  84124. 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
  84125. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  84126. };
  84127. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  84128. var q = vertex1.q.add(vertex2.q);
  84129. var border = vertex1.isBorder && vertex2.isBorder;
  84130. var error = 0;
  84131. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  84132. if (qDet !== 0 && !border) {
  84133. if (!pointResult) {
  84134. pointResult = BABYLON.Vector3.Zero();
  84135. }
  84136. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  84137. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  84138. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  84139. error = this.vertexError(q, pointResult);
  84140. }
  84141. else {
  84142. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  84143. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  84144. var error1 = this.vertexError(q, vertex1.position);
  84145. var error2 = this.vertexError(q, vertex2.position);
  84146. var error3 = this.vertexError(q, p3);
  84147. error = Math.min(error1, error2, error3);
  84148. if (error === error1) {
  84149. if (pointResult) {
  84150. pointResult.copyFrom(vertex1.position);
  84151. }
  84152. }
  84153. else if (error === error2) {
  84154. if (pointResult) {
  84155. pointResult.copyFrom(vertex2.position);
  84156. }
  84157. }
  84158. else {
  84159. if (pointResult) {
  84160. pointResult.copyFrom(p3);
  84161. }
  84162. }
  84163. }
  84164. return error;
  84165. };
  84166. return QuadraticErrorSimplification;
  84167. }());
  84168. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  84169. })(BABYLON || (BABYLON = {}));
  84170. //# sourceMappingURL=babylon.meshSimplification.js.map
  84171. "use strict";
  84172. var BABYLON;
  84173. (function (BABYLON) {
  84174. var MeshLODLevel = /** @class */ (function () {
  84175. function MeshLODLevel(distance, mesh) {
  84176. this.distance = distance;
  84177. this.mesh = mesh;
  84178. }
  84179. return MeshLODLevel;
  84180. }());
  84181. BABYLON.MeshLODLevel = MeshLODLevel;
  84182. })(BABYLON || (BABYLON = {}));
  84183. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84184. "use strict";
  84185. var BABYLON;
  84186. (function (BABYLON) {
  84187. /**
  84188. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84189. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84190. */
  84191. var SceneOptimization = /** @class */ (function () {
  84192. /**
  84193. * Creates the SceneOptimization object
  84194. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84195. * @param desc defines the description associated with the optimization
  84196. */
  84197. function SceneOptimization(
  84198. /**
  84199. * Defines the priority of this optimization (0 by default which means first in the list)
  84200. */
  84201. priority) {
  84202. if (priority === void 0) { priority = 0; }
  84203. this.priority = priority;
  84204. }
  84205. /**
  84206. * Gets a string describing the action executed by the current optimization
  84207. * @returns description string
  84208. */
  84209. SceneOptimization.prototype.getDescription = function () {
  84210. return "";
  84211. };
  84212. /**
  84213. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84214. * @param scene defines the current scene where to apply this optimization
  84215. * @param optimizer defines the current optimizer
  84216. * @returns true if everything that can be done was applied
  84217. */
  84218. SceneOptimization.prototype.apply = function (scene, optimizer) {
  84219. return true;
  84220. };
  84221. ;
  84222. return SceneOptimization;
  84223. }());
  84224. BABYLON.SceneOptimization = SceneOptimization;
  84225. /**
  84226. * Defines an optimization used to reduce the size of render target textures
  84227. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84228. */
  84229. var TextureOptimization = /** @class */ (function (_super) {
  84230. __extends(TextureOptimization, _super);
  84231. /**
  84232. * Creates the TextureOptimization object
  84233. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84234. * @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
  84235. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84236. */
  84237. function TextureOptimization(
  84238. /**
  84239. * Defines the priority of this optimization (0 by default which means first in the list)
  84240. */
  84241. priority,
  84242. /**
  84243. * 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
  84244. */
  84245. maximumSize,
  84246. /**
  84247. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84248. */
  84249. step) {
  84250. if (priority === void 0) { priority = 0; }
  84251. if (maximumSize === void 0) { maximumSize = 1024; }
  84252. if (step === void 0) { step = 0.5; }
  84253. var _this = _super.call(this, priority) || this;
  84254. _this.priority = priority;
  84255. _this.maximumSize = maximumSize;
  84256. _this.step = step;
  84257. return _this;
  84258. }
  84259. /**
  84260. * Gets a string describing the action executed by the current optimization
  84261. * @returns description string
  84262. */
  84263. TextureOptimization.prototype.getDescription = function () {
  84264. return "Reducing render target texture size to " + this.maximumSize;
  84265. };
  84266. /**
  84267. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84268. * @param scene defines the current scene where to apply this optimization
  84269. * @param optimizer defines the current optimizer
  84270. * @returns true if everything that can be done was applied
  84271. */
  84272. TextureOptimization.prototype.apply = function (scene, optimizer) {
  84273. var allDone = true;
  84274. for (var index = 0; index < scene.textures.length; index++) {
  84275. var texture = scene.textures[index];
  84276. if (!texture.canRescale || texture.getContext) {
  84277. continue;
  84278. }
  84279. var currentSize = texture.getSize();
  84280. var maxDimension = Math.max(currentSize.width, currentSize.height);
  84281. if (maxDimension > this.maximumSize) {
  84282. texture.scale(this.step);
  84283. allDone = false;
  84284. }
  84285. }
  84286. return allDone;
  84287. };
  84288. return TextureOptimization;
  84289. }(SceneOptimization));
  84290. BABYLON.TextureOptimization = TextureOptimization;
  84291. /**
  84292. * Defines an optimization used to increase or decrease the rendering resolution
  84293. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84294. */
  84295. var HardwareScalingOptimization = /** @class */ (function (_super) {
  84296. __extends(HardwareScalingOptimization, _super);
  84297. /**
  84298. * Creates the HardwareScalingOptimization object
  84299. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84300. * @param maximumScale defines the maximum scale to use (2 by default)
  84301. * @param step defines the step to use between two passes (0.5 by default)
  84302. */
  84303. function HardwareScalingOptimization(
  84304. /**
  84305. * Defines the priority of this optimization (0 by default which means first in the list)
  84306. */
  84307. priority,
  84308. /**
  84309. * Defines the maximum scale to use (2 by default)
  84310. */
  84311. maximumScale,
  84312. /**
  84313. * Defines the step to use between two passes (0.5 by default)
  84314. */
  84315. step) {
  84316. if (priority === void 0) { priority = 0; }
  84317. if (maximumScale === void 0) { maximumScale = 2; }
  84318. if (step === void 0) { step = 0.25; }
  84319. var _this = _super.call(this, priority) || this;
  84320. _this.priority = priority;
  84321. _this.maximumScale = maximumScale;
  84322. _this.step = step;
  84323. _this._currentScale = -1;
  84324. _this._directionOffset = 1;
  84325. return _this;
  84326. }
  84327. /**
  84328. * Gets a string describing the action executed by the current optimization
  84329. * @return description string
  84330. */
  84331. HardwareScalingOptimization.prototype.getDescription = function () {
  84332. return "Setting hardware scaling level to " + this._currentScale;
  84333. };
  84334. /**
  84335. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84336. * @param scene defines the current scene where to apply this optimization
  84337. * @param optimizer defines the current optimizer
  84338. * @returns true if everything that can be done was applied
  84339. */
  84340. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  84341. if (this._currentScale === -1) {
  84342. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  84343. if (this._currentScale > this.maximumScale) {
  84344. this._directionOffset = -1;
  84345. }
  84346. }
  84347. this._currentScale += this._directionOffset * this.step;
  84348. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  84349. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  84350. };
  84351. ;
  84352. return HardwareScalingOptimization;
  84353. }(SceneOptimization));
  84354. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  84355. /**
  84356. * Defines an optimization used to remove shadows
  84357. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84358. */
  84359. var ShadowsOptimization = /** @class */ (function (_super) {
  84360. __extends(ShadowsOptimization, _super);
  84361. function ShadowsOptimization() {
  84362. return _super !== null && _super.apply(this, arguments) || this;
  84363. }
  84364. /**
  84365. * Gets a string describing the action executed by the current optimization
  84366. * @return description string
  84367. */
  84368. ShadowsOptimization.prototype.getDescription = function () {
  84369. return "Turning shadows on/off";
  84370. };
  84371. /**
  84372. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84373. * @param scene defines the current scene where to apply this optimization
  84374. * @param optimizer defines the current optimizer
  84375. * @returns true if everything that can be done was applied
  84376. */
  84377. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  84378. scene.shadowsEnabled = optimizer.isInImprovementMode;
  84379. return true;
  84380. };
  84381. ;
  84382. return ShadowsOptimization;
  84383. }(SceneOptimization));
  84384. BABYLON.ShadowsOptimization = ShadowsOptimization;
  84385. /**
  84386. * Defines an optimization used to turn post-processes off
  84387. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84388. */
  84389. var PostProcessesOptimization = /** @class */ (function (_super) {
  84390. __extends(PostProcessesOptimization, _super);
  84391. function PostProcessesOptimization() {
  84392. return _super !== null && _super.apply(this, arguments) || this;
  84393. }
  84394. /**
  84395. * Gets a string describing the action executed by the current optimization
  84396. * @return description string
  84397. */
  84398. PostProcessesOptimization.prototype.getDescription = function () {
  84399. return "Turning post-processes on/off";
  84400. };
  84401. /**
  84402. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84403. * @param scene defines the current scene where to apply this optimization
  84404. * @param optimizer defines the current optimizer
  84405. * @returns true if everything that can be done was applied
  84406. */
  84407. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  84408. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  84409. return true;
  84410. };
  84411. ;
  84412. return PostProcessesOptimization;
  84413. }(SceneOptimization));
  84414. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  84415. /**
  84416. * Defines an optimization used to turn lens flares off
  84417. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84418. */
  84419. var LensFlaresOptimization = /** @class */ (function (_super) {
  84420. __extends(LensFlaresOptimization, _super);
  84421. function LensFlaresOptimization() {
  84422. return _super !== null && _super.apply(this, arguments) || this;
  84423. }
  84424. /**
  84425. * Gets a string describing the action executed by the current optimization
  84426. * @return description string
  84427. */
  84428. LensFlaresOptimization.prototype.getDescription = function () {
  84429. return "Turning lens flares on/off";
  84430. };
  84431. /**
  84432. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84433. * @param scene defines the current scene where to apply this optimization
  84434. * @param optimizer defines the current optimizer
  84435. * @returns true if everything that can be done was applied
  84436. */
  84437. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  84438. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  84439. return true;
  84440. };
  84441. ;
  84442. return LensFlaresOptimization;
  84443. }(SceneOptimization));
  84444. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  84445. /**
  84446. * Defines an optimization based on user defined callback.
  84447. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84448. */
  84449. var CustomOptimization = /** @class */ (function (_super) {
  84450. __extends(CustomOptimization, _super);
  84451. function CustomOptimization() {
  84452. return _super !== null && _super.apply(this, arguments) || this;
  84453. }
  84454. /**
  84455. * Gets a string describing the action executed by the current optimization
  84456. * @returns description string
  84457. */
  84458. CustomOptimization.prototype.getDescription = function () {
  84459. if (this.onGetDescription) {
  84460. return this.onGetDescription();
  84461. }
  84462. return "Running user defined callback";
  84463. };
  84464. /**
  84465. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84466. * @param scene defines the current scene where to apply this optimization
  84467. * @param optimizer defines the current optimizer
  84468. * @returns true if everything that can be done was applied
  84469. */
  84470. CustomOptimization.prototype.apply = function (scene, optimizer) {
  84471. if (this.onApply) {
  84472. return this.onApply(scene, optimizer);
  84473. }
  84474. return true;
  84475. };
  84476. ;
  84477. return CustomOptimization;
  84478. }(SceneOptimization));
  84479. BABYLON.CustomOptimization = CustomOptimization;
  84480. /**
  84481. * Defines an optimization used to turn particles off
  84482. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84483. */
  84484. var ParticlesOptimization = /** @class */ (function (_super) {
  84485. __extends(ParticlesOptimization, _super);
  84486. function ParticlesOptimization() {
  84487. return _super !== null && _super.apply(this, arguments) || this;
  84488. }
  84489. /**
  84490. * Gets a string describing the action executed by the current optimization
  84491. * @return description string
  84492. */
  84493. ParticlesOptimization.prototype.getDescription = function () {
  84494. return "Turning particles on/off";
  84495. };
  84496. /**
  84497. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84498. * @param scene defines the current scene where to apply this optimization
  84499. * @param optimizer defines the current optimizer
  84500. * @returns true if everything that can be done was applied
  84501. */
  84502. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  84503. scene.particlesEnabled = optimizer.isInImprovementMode;
  84504. return true;
  84505. };
  84506. ;
  84507. return ParticlesOptimization;
  84508. }(SceneOptimization));
  84509. BABYLON.ParticlesOptimization = ParticlesOptimization;
  84510. /**
  84511. * Defines an optimization used to turn render targets off
  84512. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84513. */
  84514. var RenderTargetsOptimization = /** @class */ (function (_super) {
  84515. __extends(RenderTargetsOptimization, _super);
  84516. function RenderTargetsOptimization() {
  84517. return _super !== null && _super.apply(this, arguments) || this;
  84518. }
  84519. /**
  84520. * Gets a string describing the action executed by the current optimization
  84521. * @return description string
  84522. */
  84523. RenderTargetsOptimization.prototype.getDescription = function () {
  84524. return "Turning render targets off";
  84525. };
  84526. /**
  84527. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84528. * @param scene defines the current scene where to apply this optimization
  84529. * @param optimizer defines the current optimizer
  84530. * @returns true if everything that can be done was applied
  84531. */
  84532. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  84533. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  84534. return true;
  84535. };
  84536. ;
  84537. return RenderTargetsOptimization;
  84538. }(SceneOptimization));
  84539. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  84540. /**
  84541. * Defines an optimization used to merge meshes with compatible materials
  84542. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84543. */
  84544. var MergeMeshesOptimization = /** @class */ (function (_super) {
  84545. __extends(MergeMeshesOptimization, _super);
  84546. function MergeMeshesOptimization() {
  84547. var _this = _super !== null && _super.apply(this, arguments) || this;
  84548. _this._canBeMerged = function (abstractMesh) {
  84549. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  84550. return false;
  84551. }
  84552. var mesh = abstractMesh;
  84553. if (!mesh.isVisible || !mesh.isEnabled()) {
  84554. return false;
  84555. }
  84556. if (mesh.instances.length > 0) {
  84557. return false;
  84558. }
  84559. if (mesh.skeleton || mesh.hasLODLevels) {
  84560. return false;
  84561. }
  84562. if (mesh.parent) {
  84563. return false;
  84564. }
  84565. return true;
  84566. };
  84567. return _this;
  84568. }
  84569. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  84570. /**
  84571. * Gets or sets a boolean which defines if optimization octree has to be updated
  84572. */
  84573. get: function () {
  84574. return MergeMeshesOptimization._UpdateSelectionTree;
  84575. },
  84576. /**
  84577. * Gets or sets a boolean which defines if optimization octree has to be updated
  84578. */
  84579. set: function (value) {
  84580. MergeMeshesOptimization._UpdateSelectionTree = value;
  84581. },
  84582. enumerable: true,
  84583. configurable: true
  84584. });
  84585. /**
  84586. * Gets a string describing the action executed by the current optimization
  84587. * @return description string
  84588. */
  84589. MergeMeshesOptimization.prototype.getDescription = function () {
  84590. return "Merging similar meshes together";
  84591. };
  84592. /**
  84593. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84594. * @param scene defines the current scene where to apply this optimization
  84595. * @param optimizer defines the current optimizer
  84596. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  84597. * @returns true if everything that can be done was applied
  84598. */
  84599. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  84600. var globalPool = scene.meshes.slice(0);
  84601. var globalLength = globalPool.length;
  84602. for (var index = 0; index < globalLength; index++) {
  84603. var currentPool = new Array();
  84604. var current = globalPool[index];
  84605. // Checks
  84606. if (!this._canBeMerged(current)) {
  84607. continue;
  84608. }
  84609. currentPool.push(current);
  84610. // Find compatible meshes
  84611. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  84612. var otherMesh = globalPool[subIndex];
  84613. if (!this._canBeMerged(otherMesh)) {
  84614. continue;
  84615. }
  84616. if (otherMesh.material !== current.material) {
  84617. continue;
  84618. }
  84619. if (otherMesh.checkCollisions !== current.checkCollisions) {
  84620. continue;
  84621. }
  84622. currentPool.push(otherMesh);
  84623. globalLength--;
  84624. globalPool.splice(subIndex, 1);
  84625. subIndex--;
  84626. }
  84627. if (currentPool.length < 2) {
  84628. continue;
  84629. }
  84630. // Merge meshes
  84631. BABYLON.Mesh.MergeMeshes(currentPool);
  84632. }
  84633. if (updateSelectionTree != undefined) {
  84634. if (updateSelectionTree) {
  84635. scene.createOrUpdateSelectionOctree();
  84636. }
  84637. }
  84638. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  84639. scene.createOrUpdateSelectionOctree();
  84640. }
  84641. return true;
  84642. };
  84643. ;
  84644. MergeMeshesOptimization._UpdateSelectionTree = false;
  84645. return MergeMeshesOptimization;
  84646. }(SceneOptimization));
  84647. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  84648. /**
  84649. * Defines a list of options used by SceneOptimizer
  84650. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84651. */
  84652. var SceneOptimizerOptions = /** @class */ (function () {
  84653. /**
  84654. * Creates a new list of options used by SceneOptimizer
  84655. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  84656. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  84657. */
  84658. function SceneOptimizerOptions(
  84659. /**
  84660. * Defines the target frame rate to reach (60 by default)
  84661. */
  84662. targetFrameRate,
  84663. /**
  84664. * Defines the interval between two checkes (2000ms by default)
  84665. */
  84666. trackerDuration) {
  84667. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  84668. if (trackerDuration === void 0) { trackerDuration = 2000; }
  84669. this.targetFrameRate = targetFrameRate;
  84670. this.trackerDuration = trackerDuration;
  84671. /**
  84672. * Gets the list of optimizations to apply
  84673. */
  84674. this.optimizations = new Array();
  84675. }
  84676. /**
  84677. * Add a new optimization
  84678. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  84679. * @returns the current SceneOptimizerOptions
  84680. */
  84681. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  84682. this.optimizations.push(optimization);
  84683. return this;
  84684. };
  84685. /**
  84686. * Add a new custom optimization
  84687. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  84688. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  84689. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84690. * @returns the current SceneOptimizerOptions
  84691. */
  84692. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  84693. if (priority === void 0) { priority = 0; }
  84694. var optimization = new CustomOptimization(priority);
  84695. optimization.onApply = onApply;
  84696. optimization.onGetDescription = onGetDescription;
  84697. this.optimizations.push(optimization);
  84698. return this;
  84699. };
  84700. /**
  84701. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  84702. * @param targetFrameRate defines the target frame rate (60 by default)
  84703. * @returns a SceneOptimizerOptions object
  84704. */
  84705. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  84706. var result = new SceneOptimizerOptions(targetFrameRate);
  84707. var priority = 0;
  84708. result.addOptimization(new MergeMeshesOptimization(priority));
  84709. result.addOptimization(new ShadowsOptimization(priority));
  84710. result.addOptimization(new LensFlaresOptimization(priority));
  84711. // Next priority
  84712. priority++;
  84713. result.addOptimization(new PostProcessesOptimization(priority));
  84714. result.addOptimization(new ParticlesOptimization(priority));
  84715. // Next priority
  84716. priority++;
  84717. result.addOptimization(new TextureOptimization(priority, 1024));
  84718. return result;
  84719. };
  84720. /**
  84721. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  84722. * @param targetFrameRate defines the target frame rate (60 by default)
  84723. * @returns a SceneOptimizerOptions object
  84724. */
  84725. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  84726. var result = new SceneOptimizerOptions(targetFrameRate);
  84727. var priority = 0;
  84728. result.addOptimization(new MergeMeshesOptimization(priority));
  84729. result.addOptimization(new ShadowsOptimization(priority));
  84730. result.addOptimization(new LensFlaresOptimization(priority));
  84731. // Next priority
  84732. priority++;
  84733. result.addOptimization(new PostProcessesOptimization(priority));
  84734. result.addOptimization(new ParticlesOptimization(priority));
  84735. // Next priority
  84736. priority++;
  84737. result.addOptimization(new TextureOptimization(priority, 512));
  84738. // Next priority
  84739. priority++;
  84740. result.addOptimization(new RenderTargetsOptimization(priority));
  84741. // Next priority
  84742. priority++;
  84743. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  84744. return result;
  84745. };
  84746. /**
  84747. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  84748. * @param targetFrameRate defines the target frame rate (60 by default)
  84749. * @returns a SceneOptimizerOptions object
  84750. */
  84751. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  84752. var result = new SceneOptimizerOptions(targetFrameRate);
  84753. var priority = 0;
  84754. result.addOptimization(new MergeMeshesOptimization(priority));
  84755. result.addOptimization(new ShadowsOptimization(priority));
  84756. result.addOptimization(new LensFlaresOptimization(priority));
  84757. // Next priority
  84758. priority++;
  84759. result.addOptimization(new PostProcessesOptimization(priority));
  84760. result.addOptimization(new ParticlesOptimization(priority));
  84761. // Next priority
  84762. priority++;
  84763. result.addOptimization(new TextureOptimization(priority, 256));
  84764. // Next priority
  84765. priority++;
  84766. result.addOptimization(new RenderTargetsOptimization(priority));
  84767. // Next priority
  84768. priority++;
  84769. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  84770. return result;
  84771. };
  84772. return SceneOptimizerOptions;
  84773. }());
  84774. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  84775. /**
  84776. * Class used to run optimizations in order to reach a target frame rate
  84777. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84778. */
  84779. var SceneOptimizer = /** @class */ (function () {
  84780. /**
  84781. * Creates a new SceneOptimizer
  84782. * @param scene defines the scene to work on
  84783. * @param options defines the options to use with the SceneOptimizer
  84784. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  84785. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  84786. */
  84787. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  84788. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  84789. if (improvementMode === void 0) { improvementMode = false; }
  84790. var _this = this;
  84791. this._isRunning = false;
  84792. this._currentPriorityLevel = 0;
  84793. this._targetFrameRate = 60;
  84794. this._trackerDuration = 2000;
  84795. this._currentFrameRate = 0;
  84796. this._improvementMode = false;
  84797. /**
  84798. * Defines an observable called when the optimizer reaches the target frame rate
  84799. */
  84800. this.onSuccessObservable = new BABYLON.Observable();
  84801. /**
  84802. * Defines an observable called when the optimizer enables an optimization
  84803. */
  84804. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  84805. /**
  84806. * Defines an observable called when the optimizer is not able to reach the target frame rate
  84807. */
  84808. this.onFailureObservable = new BABYLON.Observable();
  84809. if (!options) {
  84810. this._options = new SceneOptimizerOptions();
  84811. }
  84812. else {
  84813. this._options = options;
  84814. }
  84815. if (this._options.targetFrameRate) {
  84816. this._targetFrameRate = this._options.targetFrameRate;
  84817. }
  84818. if (this._options.trackerDuration) {
  84819. this._trackerDuration = this._options.trackerDuration;
  84820. }
  84821. if (autoGeneratePriorities) {
  84822. var priority = 0;
  84823. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  84824. var optim = _a[_i];
  84825. optim.priority = priority++;
  84826. }
  84827. }
  84828. this._improvementMode = improvementMode;
  84829. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84830. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  84831. _this._sceneDisposeObserver = null;
  84832. _this.dispose();
  84833. });
  84834. }
  84835. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  84836. /**
  84837. * Gets a boolean indicating if the optimizer is in improvement mode
  84838. */
  84839. get: function () {
  84840. return this._improvementMode;
  84841. },
  84842. enumerable: true,
  84843. configurable: true
  84844. });
  84845. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  84846. /**
  84847. * Gets the current priority level (0 at start)
  84848. */
  84849. get: function () {
  84850. return this._currentPriorityLevel;
  84851. },
  84852. enumerable: true,
  84853. configurable: true
  84854. });
  84855. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  84856. /**
  84857. * Gets the current frame rate checked by the SceneOptimizer
  84858. */
  84859. get: function () {
  84860. return this._currentFrameRate;
  84861. },
  84862. enumerable: true,
  84863. configurable: true
  84864. });
  84865. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  84866. /**
  84867. * Gets or sets the current target frame rate (60 by default)
  84868. */
  84869. get: function () {
  84870. return this._targetFrameRate;
  84871. },
  84872. /**
  84873. * Gets or sets the current target frame rate (60 by default)
  84874. */
  84875. set: function (value) {
  84876. this._targetFrameRate = value;
  84877. },
  84878. enumerable: true,
  84879. configurable: true
  84880. });
  84881. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  84882. /**
  84883. * Gets or sets the current interval between two checks (every 2000ms by default)
  84884. */
  84885. get: function () {
  84886. return this._trackerDuration;
  84887. },
  84888. /**
  84889. * Gets or sets the current interval between two checks (every 2000ms by default)
  84890. */
  84891. set: function (value) {
  84892. this._trackerDuration = value;
  84893. },
  84894. enumerable: true,
  84895. configurable: true
  84896. });
  84897. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  84898. /**
  84899. * Gets the list of active optimizations
  84900. */
  84901. get: function () {
  84902. return this._options.optimizations;
  84903. },
  84904. enumerable: true,
  84905. configurable: true
  84906. });
  84907. /**
  84908. * Stops the current optimizer
  84909. */
  84910. SceneOptimizer.prototype.stop = function () {
  84911. this._isRunning = false;
  84912. };
  84913. /**
  84914. * Reset the optimizer to initial step (current priority level = 0)
  84915. */
  84916. SceneOptimizer.prototype.reset = function () {
  84917. this._currentPriorityLevel = 0;
  84918. };
  84919. /**
  84920. * Start the optimizer. By default it will try to reach a specific framerate
  84921. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  84922. */
  84923. SceneOptimizer.prototype.start = function () {
  84924. var _this = this;
  84925. if (this._isRunning) {
  84926. return;
  84927. }
  84928. this._isRunning = true;
  84929. // Let's wait for the scene to be ready before running our check
  84930. this._scene.executeWhenReady(function () {
  84931. setTimeout(function () {
  84932. _this._checkCurrentState();
  84933. }, _this._trackerDuration);
  84934. });
  84935. };
  84936. SceneOptimizer.prototype._checkCurrentState = function () {
  84937. var _this = this;
  84938. if (!this._isRunning) {
  84939. return;
  84940. }
  84941. var scene = this._scene;
  84942. var options = this._options;
  84943. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  84944. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  84945. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  84946. this._isRunning = false;
  84947. this.onSuccessObservable.notifyObservers(this);
  84948. return;
  84949. }
  84950. // Apply current level of optimizations
  84951. var allDone = true;
  84952. var noOptimizationApplied = true;
  84953. for (var index = 0; index < options.optimizations.length; index++) {
  84954. var optimization = options.optimizations[index];
  84955. if (optimization.priority === this._currentPriorityLevel) {
  84956. noOptimizationApplied = false;
  84957. allDone = allDone && optimization.apply(scene, this);
  84958. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  84959. }
  84960. }
  84961. // If no optimization was applied, this is a failure :(
  84962. if (noOptimizationApplied) {
  84963. this._isRunning = false;
  84964. this.onFailureObservable.notifyObservers(this);
  84965. return;
  84966. }
  84967. // If all optimizations were done, move to next level
  84968. if (allDone) {
  84969. this._currentPriorityLevel++;
  84970. }
  84971. // Let's the system running for a specific amount of time before checking FPS
  84972. scene.executeWhenReady(function () {
  84973. setTimeout(function () {
  84974. _this._checkCurrentState();
  84975. }, _this._trackerDuration);
  84976. });
  84977. };
  84978. /**
  84979. * Release all resources
  84980. */
  84981. SceneOptimizer.prototype.dispose = function () {
  84982. this.stop();
  84983. this.onSuccessObservable.clear();
  84984. this.onFailureObservable.clear();
  84985. this.onNewOptimizationAppliedObservable.clear();
  84986. if (this._sceneDisposeObserver) {
  84987. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  84988. }
  84989. };
  84990. /**
  84991. * Helper function to create a SceneOptimizer with one single line of code
  84992. * @param scene defines the scene to work on
  84993. * @param options defines the options to use with the SceneOptimizer
  84994. * @param onSuccess defines a callback to call on success
  84995. * @param onFailure defines a callback to call on failure
  84996. * @returns the new SceneOptimizer object
  84997. */
  84998. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  84999. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  85000. if (onSuccess) {
  85001. optimizer.onSuccessObservable.add(function () {
  85002. onSuccess();
  85003. });
  85004. }
  85005. if (onFailure) {
  85006. optimizer.onFailureObservable.add(function () {
  85007. onFailure();
  85008. });
  85009. }
  85010. optimizer.start();
  85011. return optimizer;
  85012. };
  85013. return SceneOptimizer;
  85014. }());
  85015. BABYLON.SceneOptimizer = SceneOptimizer;
  85016. })(BABYLON || (BABYLON = {}));
  85017. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  85018. "use strict";
  85019. var BABYLON;
  85020. (function (BABYLON) {
  85021. var OutlineRenderer = /** @class */ (function () {
  85022. function OutlineRenderer(scene) {
  85023. this.zOffset = 1;
  85024. this._scene = scene;
  85025. }
  85026. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  85027. var _this = this;
  85028. if (useOverlay === void 0) { useOverlay = false; }
  85029. var scene = this._scene;
  85030. var engine = this._scene.getEngine();
  85031. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85032. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  85033. return;
  85034. }
  85035. var mesh = subMesh.getRenderingMesh();
  85036. var material = subMesh.getMaterial();
  85037. if (!material || !scene.activeCamera) {
  85038. return;
  85039. }
  85040. engine.enableEffect(this._effect);
  85041. // Logarithmic depth
  85042. if (material.useLogarithmicDepth) {
  85043. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  85044. }
  85045. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  85046. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  85047. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85048. // Bones
  85049. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85050. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85051. }
  85052. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  85053. // Alpha test
  85054. if (material && material.needAlphaTesting()) {
  85055. var alphaTexture = material.getAlphaTestTexture();
  85056. if (alphaTexture) {
  85057. this._effect.setTexture("diffuseSampler", alphaTexture);
  85058. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85059. }
  85060. }
  85061. engine.setZOffset(-this.zOffset);
  85062. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  85063. engine.setZOffset(0);
  85064. };
  85065. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  85066. var defines = [];
  85067. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85068. var mesh = subMesh.getMesh();
  85069. var material = subMesh.getMaterial();
  85070. if (material) {
  85071. // Alpha test
  85072. if (material.needAlphaTesting()) {
  85073. defines.push("#define ALPHATEST");
  85074. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85075. attribs.push(BABYLON.VertexBuffer.UVKind);
  85076. defines.push("#define UV1");
  85077. }
  85078. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85079. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85080. defines.push("#define UV2");
  85081. }
  85082. }
  85083. //Logarithmic depth
  85084. if (material.useLogarithmicDepth) {
  85085. defines.push("#define LOGARITHMICDEPTH");
  85086. }
  85087. }
  85088. // Bones
  85089. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85090. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85091. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85092. if (mesh.numBoneInfluencers > 4) {
  85093. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85094. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85095. }
  85096. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85097. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85098. }
  85099. else {
  85100. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85101. }
  85102. // Instances
  85103. if (useInstances) {
  85104. defines.push("#define INSTANCES");
  85105. attribs.push("world0");
  85106. attribs.push("world1");
  85107. attribs.push("world2");
  85108. attribs.push("world3");
  85109. }
  85110. // Get correct effect
  85111. var join = defines.join("\n");
  85112. if (this._cachedDefines !== join) {
  85113. this._cachedDefines = join;
  85114. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  85115. }
  85116. return this._effect.isReady();
  85117. };
  85118. return OutlineRenderer;
  85119. }());
  85120. BABYLON.OutlineRenderer = OutlineRenderer;
  85121. })(BABYLON || (BABYLON = {}));
  85122. //# sourceMappingURL=babylon.outlineRenderer.js.map
  85123. "use strict";
  85124. var BABYLON;
  85125. (function (BABYLON) {
  85126. var FaceAdjacencies = /** @class */ (function () {
  85127. function FaceAdjacencies() {
  85128. this.edges = new Array();
  85129. this.edgesConnectedCount = 0;
  85130. }
  85131. return FaceAdjacencies;
  85132. }());
  85133. var EdgesRenderer = /** @class */ (function () {
  85134. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  85135. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  85136. if (epsilon === void 0) { epsilon = 0.95; }
  85137. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  85138. this.edgesWidthScalerForOrthographic = 1000.0;
  85139. this.edgesWidthScalerForPerspective = 50.0;
  85140. this._linesPositions = new Array();
  85141. this._linesNormals = new Array();
  85142. this._linesIndices = new Array();
  85143. this._buffers = {};
  85144. this._checkVerticesInsteadOfIndices = false;
  85145. this._source = source;
  85146. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  85147. this._epsilon = epsilon;
  85148. this._prepareRessources();
  85149. this._generateEdgesLines();
  85150. }
  85151. EdgesRenderer.prototype._prepareRessources = function () {
  85152. if (this._lineShader) {
  85153. return;
  85154. }
  85155. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  85156. attributes: ["position", "normal"],
  85157. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  85158. });
  85159. this._lineShader.disableDepthWrite = true;
  85160. this._lineShader.backFaceCulling = false;
  85161. };
  85162. EdgesRenderer.prototype._rebuild = function () {
  85163. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85164. if (buffer) {
  85165. buffer._rebuild();
  85166. }
  85167. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85168. if (buffer) {
  85169. buffer._rebuild();
  85170. }
  85171. var scene = this._source.getScene();
  85172. var engine = scene.getEngine();
  85173. this._ib = engine.createIndexBuffer(this._linesIndices);
  85174. };
  85175. EdgesRenderer.prototype.dispose = function () {
  85176. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85177. if (buffer) {
  85178. buffer.dispose();
  85179. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  85180. }
  85181. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85182. if (buffer) {
  85183. buffer.dispose();
  85184. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85185. }
  85186. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85187. this._lineShader.dispose();
  85188. };
  85189. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85190. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85191. return 0;
  85192. }
  85193. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85194. return 1;
  85195. }
  85196. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85197. return 2;
  85198. }
  85199. return -1;
  85200. };
  85201. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85202. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85203. return 0;
  85204. }
  85205. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85206. return 1;
  85207. }
  85208. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85209. return 2;
  85210. }
  85211. return -1;
  85212. };
  85213. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85214. var needToCreateLine;
  85215. if (edge === undefined) {
  85216. needToCreateLine = true;
  85217. }
  85218. else {
  85219. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  85220. needToCreateLine = dotProduct < this._epsilon;
  85221. }
  85222. if (needToCreateLine) {
  85223. var offset = this._linesPositions.length / 3;
  85224. var normal = p0.subtract(p1);
  85225. normal.normalize();
  85226. // Positions
  85227. this._linesPositions.push(p0.x);
  85228. this._linesPositions.push(p0.y);
  85229. this._linesPositions.push(p0.z);
  85230. this._linesPositions.push(p0.x);
  85231. this._linesPositions.push(p0.y);
  85232. this._linesPositions.push(p0.z);
  85233. this._linesPositions.push(p1.x);
  85234. this._linesPositions.push(p1.y);
  85235. this._linesPositions.push(p1.z);
  85236. this._linesPositions.push(p1.x);
  85237. this._linesPositions.push(p1.y);
  85238. this._linesPositions.push(p1.z);
  85239. // Normals
  85240. this._linesNormals.push(p1.x);
  85241. this._linesNormals.push(p1.y);
  85242. this._linesNormals.push(p1.z);
  85243. this._linesNormals.push(-1);
  85244. this._linesNormals.push(p1.x);
  85245. this._linesNormals.push(p1.y);
  85246. this._linesNormals.push(p1.z);
  85247. this._linesNormals.push(1);
  85248. this._linesNormals.push(p0.x);
  85249. this._linesNormals.push(p0.y);
  85250. this._linesNormals.push(p0.z);
  85251. this._linesNormals.push(-1);
  85252. this._linesNormals.push(p0.x);
  85253. this._linesNormals.push(p0.y);
  85254. this._linesNormals.push(p0.z);
  85255. this._linesNormals.push(1);
  85256. // Indices
  85257. this._linesIndices.push(offset);
  85258. this._linesIndices.push(offset + 1);
  85259. this._linesIndices.push(offset + 2);
  85260. this._linesIndices.push(offset);
  85261. this._linesIndices.push(offset + 2);
  85262. this._linesIndices.push(offset + 3);
  85263. }
  85264. };
  85265. EdgesRenderer.prototype._generateEdgesLines = function () {
  85266. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85267. var indices = this._source.getIndices();
  85268. if (!indices || !positions) {
  85269. return;
  85270. }
  85271. // First let's find adjacencies
  85272. var adjacencies = new Array();
  85273. var faceNormals = new Array();
  85274. var index;
  85275. var faceAdjacencies;
  85276. // Prepare faces
  85277. for (index = 0; index < indices.length; index += 3) {
  85278. faceAdjacencies = new FaceAdjacencies();
  85279. var p0Index = indices[index];
  85280. var p1Index = indices[index + 1];
  85281. var p2Index = indices[index + 2];
  85282. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  85283. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  85284. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  85285. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  85286. faceNormal.normalize();
  85287. faceNormals.push(faceNormal);
  85288. adjacencies.push(faceAdjacencies);
  85289. }
  85290. // Scan
  85291. for (index = 0; index < adjacencies.length; index++) {
  85292. faceAdjacencies = adjacencies[index];
  85293. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  85294. var otherFaceAdjacencies = adjacencies[otherIndex];
  85295. if (faceAdjacencies.edgesConnectedCount === 3) {
  85296. break;
  85297. }
  85298. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  85299. continue;
  85300. }
  85301. var otherP0 = indices[otherIndex * 3];
  85302. var otherP1 = indices[otherIndex * 3 + 1];
  85303. var otherP2 = indices[otherIndex * 3 + 2];
  85304. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  85305. var otherEdgeIndex = 0;
  85306. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  85307. continue;
  85308. }
  85309. switch (edgeIndex) {
  85310. case 0:
  85311. if (this._checkVerticesInsteadOfIndices) {
  85312. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85313. }
  85314. else {
  85315. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  85316. }
  85317. break;
  85318. case 1:
  85319. if (this._checkVerticesInsteadOfIndices) {
  85320. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85321. }
  85322. else {
  85323. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  85324. }
  85325. break;
  85326. case 2:
  85327. if (this._checkVerticesInsteadOfIndices) {
  85328. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  85329. }
  85330. else {
  85331. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  85332. }
  85333. break;
  85334. }
  85335. if (otherEdgeIndex === -1) {
  85336. continue;
  85337. }
  85338. faceAdjacencies.edges[edgeIndex] = otherIndex;
  85339. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  85340. faceAdjacencies.edgesConnectedCount++;
  85341. otherFaceAdjacencies.edgesConnectedCount++;
  85342. if (faceAdjacencies.edgesConnectedCount === 3) {
  85343. break;
  85344. }
  85345. }
  85346. }
  85347. }
  85348. // Create lines
  85349. for (index = 0; index < adjacencies.length; index++) {
  85350. // 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
  85351. var current = adjacencies[index];
  85352. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  85353. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  85354. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  85355. }
  85356. // Merge into a single mesh
  85357. var engine = this._source.getScene().getEngine();
  85358. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  85359. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  85360. this._ib = engine.createIndexBuffer(this._linesIndices);
  85361. this._indicesCount = this._linesIndices.length;
  85362. };
  85363. EdgesRenderer.prototype.render = function () {
  85364. var scene = this._source.getScene();
  85365. if (!this._lineShader.isReady() || !scene.activeCamera) {
  85366. return;
  85367. }
  85368. var engine = scene.getEngine();
  85369. this._lineShader._preBind();
  85370. // VBOs
  85371. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  85372. scene.resetCachedMaterial();
  85373. this._lineShader.setColor4("color", this._source.edgesColor);
  85374. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  85375. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  85376. }
  85377. else {
  85378. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  85379. }
  85380. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  85381. this._lineShader.bind(this._source.getWorldMatrix());
  85382. // Draw order
  85383. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  85384. this._lineShader.unbind();
  85385. engine.setDepthWrite(true);
  85386. };
  85387. return EdgesRenderer;
  85388. }());
  85389. BABYLON.EdgesRenderer = EdgesRenderer;
  85390. })(BABYLON || (BABYLON = {}));
  85391. //# sourceMappingURL=babylon.edgesRenderer.js.map
  85392. "use strict";
  85393. var __assign = (this && this.__assign) || Object.assign || function(t) {
  85394. for (var s, i = 1, n = arguments.length; i < n; i++) {
  85395. s = arguments[i];
  85396. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  85397. t[p] = s[p];
  85398. }
  85399. return t;
  85400. };
  85401. var BABYLON;
  85402. (function (BABYLON) {
  85403. /**
  85404. * The effect layer Helps adding post process effect blended with the main pass.
  85405. *
  85406. * This can be for instance use to generate glow or higlight effects on the scene.
  85407. *
  85408. * The effect layer class can not be used directly and is intented to inherited from to be
  85409. * customized per effects.
  85410. */
  85411. var EffectLayer = /** @class */ (function () {
  85412. /**
  85413. * Instantiates a new effect Layer and references it in the scene.
  85414. * @param name The name of the layer
  85415. * @param scene The scene to use the layer in
  85416. */
  85417. function EffectLayer(
  85418. /** The Friendly of the effect in the scene */
  85419. name, scene) {
  85420. this.name = name;
  85421. this._vertexBuffers = {};
  85422. this._maxSize = 0;
  85423. this._mainTextureDesiredSize = { width: 0, height: 0 };
  85424. this._shouldRender = true;
  85425. this._postProcesses = [];
  85426. this._textures = [];
  85427. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  85428. /**
  85429. * The clear color of the texture used to generate the glow map.
  85430. */
  85431. this.neutralColor = new BABYLON.Color4();
  85432. /**
  85433. * Specifies wether the highlight layer is enabled or not.
  85434. */
  85435. this.isEnabled = true;
  85436. /**
  85437. * An event triggered when the effect layer has been disposed.
  85438. */
  85439. this.onDisposeObservable = new BABYLON.Observable();
  85440. /**
  85441. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  85442. */
  85443. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  85444. /**
  85445. * An event triggered when the generated texture is being merged in the scene.
  85446. */
  85447. this.onBeforeComposeObservable = new BABYLON.Observable();
  85448. /**
  85449. * An event triggered when the generated texture has been merged in the scene.
  85450. */
  85451. this.onAfterComposeObservable = new BABYLON.Observable();
  85452. /**
  85453. * An event triggered when the efffect layer changes its size.
  85454. */
  85455. this.onSizeChangedObservable = new BABYLON.Observable();
  85456. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85457. this._engine = scene.getEngine();
  85458. this._maxSize = this._engine.getCaps().maxTextureSize;
  85459. this._scene.effectLayers.push(this);
  85460. // Generate Buffers
  85461. this._generateIndexBuffer();
  85462. this._genrateVertexBuffer();
  85463. }
  85464. Object.defineProperty(EffectLayer.prototype, "camera", {
  85465. /**
  85466. * Gets the camera attached to the layer.
  85467. */
  85468. get: function () {
  85469. return this._effectLayerOptions.camera;
  85470. },
  85471. enumerable: true,
  85472. configurable: true
  85473. });
  85474. /**
  85475. * Initializes the effect layer with the required options.
  85476. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  85477. */
  85478. EffectLayer.prototype._init = function (options) {
  85479. // Adapt options
  85480. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85481. this._setMainTextureSize();
  85482. this._createMainTexture();
  85483. this._createTextureAndPostProcesses();
  85484. this._mergeEffect = this._createMergeEffect();
  85485. };
  85486. /**
  85487. * Generates the index buffer of the full screen quad blending to the main canvas.
  85488. */
  85489. EffectLayer.prototype._generateIndexBuffer = function () {
  85490. // Indices
  85491. var indices = [];
  85492. indices.push(0);
  85493. indices.push(1);
  85494. indices.push(2);
  85495. indices.push(0);
  85496. indices.push(2);
  85497. indices.push(3);
  85498. this._indexBuffer = this._engine.createIndexBuffer(indices);
  85499. };
  85500. /**
  85501. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  85502. */
  85503. EffectLayer.prototype._genrateVertexBuffer = function () {
  85504. // VBO
  85505. var vertices = [];
  85506. vertices.push(1, 1);
  85507. vertices.push(-1, 1);
  85508. vertices.push(-1, -1);
  85509. vertices.push(1, -1);
  85510. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85511. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  85512. };
  85513. /**
  85514. * Sets the main texture desired size which is the closest power of two
  85515. * of the engine canvas size.
  85516. */
  85517. EffectLayer.prototype._setMainTextureSize = function () {
  85518. if (this._effectLayerOptions.mainTextureFixedSize) {
  85519. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  85520. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  85521. }
  85522. else {
  85523. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  85524. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  85525. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  85526. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  85527. }
  85528. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  85529. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  85530. };
  85531. /**
  85532. * Creates the main texture for the effect layer.
  85533. */
  85534. EffectLayer.prototype._createMainTexture = function () {
  85535. var _this = this;
  85536. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  85537. width: this._mainTextureDesiredSize.width,
  85538. height: this._mainTextureDesiredSize.height
  85539. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85540. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  85541. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85542. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85543. this._mainTexture.anisotropicFilteringLevel = 1;
  85544. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85545. this._mainTexture.renderParticles = false;
  85546. this._mainTexture.renderList = null;
  85547. this._mainTexture.ignoreCameraViewport = true;
  85548. // Custom render function
  85549. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  85550. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  85551. var index;
  85552. var engine = _this._scene.getEngine();
  85553. if (depthOnlySubMeshes.length) {
  85554. engine.setColorWrite(false);
  85555. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  85556. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  85557. }
  85558. engine.setColorWrite(true);
  85559. }
  85560. for (index = 0; index < opaqueSubMeshes.length; index++) {
  85561. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  85562. }
  85563. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  85564. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  85565. }
  85566. for (index = 0; index < transparentSubMeshes.length; index++) {
  85567. _this._renderSubMesh(transparentSubMeshes.data[index]);
  85568. }
  85569. };
  85570. this._mainTexture.onClearObservable.add(function (engine) {
  85571. engine.clear(_this.neutralColor, true, true, true);
  85572. });
  85573. };
  85574. /**
  85575. * Checks for the readiness of the element composing the layer.
  85576. * @param subMesh the mesh to check for
  85577. * @param useInstances specify wether or not to use instances to render the mesh
  85578. * @param emissiveTexture the associated emissive texture used to generate the glow
  85579. * @return true if ready otherwise, false
  85580. */
  85581. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  85582. var material = subMesh.getMaterial();
  85583. if (!material) {
  85584. return false;
  85585. }
  85586. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  85587. return false;
  85588. }
  85589. var defines = [];
  85590. var attribs = [BABYLON.VertexBuffer.PositionKind];
  85591. var mesh = subMesh.getMesh();
  85592. var uv1 = false;
  85593. var uv2 = false;
  85594. // Alpha test
  85595. if (material && material.needAlphaTesting()) {
  85596. var alphaTexture = material.getAlphaTestTexture();
  85597. if (alphaTexture) {
  85598. defines.push("#define ALPHATEST");
  85599. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85600. alphaTexture.coordinatesIndex === 1) {
  85601. defines.push("#define DIFFUSEUV2");
  85602. uv2 = true;
  85603. }
  85604. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85605. defines.push("#define DIFFUSEUV1");
  85606. uv1 = true;
  85607. }
  85608. }
  85609. }
  85610. // Emissive
  85611. if (emissiveTexture) {
  85612. defines.push("#define EMISSIVE");
  85613. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  85614. emissiveTexture.coordinatesIndex === 1) {
  85615. defines.push("#define EMISSIVEUV2");
  85616. uv2 = true;
  85617. }
  85618. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85619. defines.push("#define EMISSIVEUV1");
  85620. uv1 = true;
  85621. }
  85622. }
  85623. if (uv1) {
  85624. attribs.push(BABYLON.VertexBuffer.UVKind);
  85625. defines.push("#define UV1");
  85626. }
  85627. if (uv2) {
  85628. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85629. defines.push("#define UV2");
  85630. }
  85631. // Bones
  85632. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85633. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85634. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85635. if (mesh.numBoneInfluencers > 4) {
  85636. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85637. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85638. }
  85639. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85640. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  85641. }
  85642. else {
  85643. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85644. }
  85645. // Instances
  85646. if (useInstances) {
  85647. defines.push("#define INSTANCES");
  85648. attribs.push("world0");
  85649. attribs.push("world1");
  85650. attribs.push("world2");
  85651. attribs.push("world3");
  85652. }
  85653. // Get correct effect
  85654. var join = defines.join("\n");
  85655. if (this._cachedDefines !== join) {
  85656. this._cachedDefines = join;
  85657. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  85658. }
  85659. return this._effectLayerMapGenerationEffect.isReady();
  85660. };
  85661. /**
  85662. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  85663. */
  85664. EffectLayer.prototype.render = function () {
  85665. var currentEffect = this._mergeEffect;
  85666. // Check
  85667. if (!currentEffect.isReady())
  85668. return;
  85669. for (var i = 0; i < this._postProcesses.length; i++) {
  85670. if (!this._postProcesses[i].isReady()) {
  85671. return;
  85672. }
  85673. }
  85674. var engine = this._scene.getEngine();
  85675. this.onBeforeComposeObservable.notifyObservers(this);
  85676. // Render
  85677. engine.enableEffect(currentEffect);
  85678. engine.setState(false);
  85679. // VBOs
  85680. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85681. // Cache
  85682. var previousAlphaMode = engine.getAlphaMode();
  85683. // Go Blend.
  85684. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  85685. // Blends the map on the main canvas.
  85686. this._internalRender(currentEffect);
  85687. // Restore Alpha
  85688. engine.setAlphaMode(previousAlphaMode);
  85689. this.onAfterComposeObservable.notifyObservers(this);
  85690. // Handle size changes.
  85691. var size = this._mainTexture.getSize();
  85692. this._setMainTextureSize();
  85693. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  85694. // Recreate RTT and post processes on size change.
  85695. this.onSizeChangedObservable.notifyObservers(this);
  85696. this._disposeTextureAndPostProcesses();
  85697. this._createMainTexture();
  85698. this._createTextureAndPostProcesses();
  85699. }
  85700. };
  85701. /**
  85702. * Determine if a given mesh will be used in the current effect.
  85703. * @param mesh mesh to test
  85704. * @returns true if the mesh will be used
  85705. */
  85706. EffectLayer.prototype.hasMesh = function (mesh) {
  85707. return true;
  85708. };
  85709. /**
  85710. * Returns true if the layer contains information to display, otherwise false.
  85711. * @returns true if the glow layer should be rendered
  85712. */
  85713. EffectLayer.prototype.shouldRender = function () {
  85714. return this.isEnabled && this._shouldRender;
  85715. };
  85716. /**
  85717. * Returns true if the mesh should render, otherwise false.
  85718. * @param mesh The mesh to render
  85719. * @returns true if it should render otherwise false
  85720. */
  85721. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  85722. return true;
  85723. };
  85724. /**
  85725. * Returns true if the mesh should render, otherwise false.
  85726. * @param mesh The mesh to render
  85727. * @returns true if it should render otherwise false
  85728. */
  85729. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  85730. return true;
  85731. };
  85732. /**
  85733. * Renders the submesh passed in parameter to the generation map.
  85734. */
  85735. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  85736. var _this = this;
  85737. if (!this.shouldRender()) {
  85738. return;
  85739. }
  85740. var material = subMesh.getMaterial();
  85741. var mesh = subMesh.getRenderingMesh();
  85742. var scene = this._scene;
  85743. var engine = scene.getEngine();
  85744. if (!material) {
  85745. return;
  85746. }
  85747. // Do not block in blend mode.
  85748. if (material.needAlphaBlendingForMesh(mesh)) {
  85749. return;
  85750. }
  85751. // Culling
  85752. engine.setState(material.backFaceCulling);
  85753. // Managing instances
  85754. var batch = mesh._getInstancesRenderList(subMesh._id);
  85755. if (batch.mustReturn) {
  85756. return;
  85757. }
  85758. // Early Exit per mesh
  85759. if (!this._shouldRenderMesh(mesh)) {
  85760. return;
  85761. }
  85762. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85763. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  85764. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  85765. engine.enableEffect(this._effectLayerMapGenerationEffect);
  85766. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  85767. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  85768. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  85769. // Alpha test
  85770. if (material && material.needAlphaTesting()) {
  85771. var alphaTexture = material.getAlphaTestTexture();
  85772. if (alphaTexture) {
  85773. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  85774. var textureMatrix = alphaTexture.getTextureMatrix();
  85775. if (textureMatrix) {
  85776. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  85777. }
  85778. }
  85779. }
  85780. // Glow emissive only
  85781. if (this._emissiveTextureAndColor.texture) {
  85782. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  85783. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  85784. }
  85785. // Bones
  85786. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85787. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85788. }
  85789. // Draw
  85790. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  85791. }
  85792. else {
  85793. // Need to reset refresh rate of the shadowMap
  85794. this._mainTexture.resetRefreshCounter();
  85795. }
  85796. };
  85797. /**
  85798. * Rebuild the required buffers.
  85799. * @ignore Internal use only.
  85800. */
  85801. EffectLayer.prototype._rebuild = function () {
  85802. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85803. if (vb) {
  85804. vb._rebuild();
  85805. }
  85806. this._generateIndexBuffer();
  85807. };
  85808. /**
  85809. * Dispose only the render target textures and post process.
  85810. */
  85811. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  85812. this._mainTexture.dispose();
  85813. for (var i = 0; i < this._postProcesses.length; i++) {
  85814. if (this._postProcesses[i]) {
  85815. this._postProcesses[i].dispose();
  85816. }
  85817. }
  85818. this._postProcesses = [];
  85819. for (var i = 0; i < this._textures.length; i++) {
  85820. if (this._textures[i]) {
  85821. this._textures[i].dispose();
  85822. }
  85823. }
  85824. this._textures = [];
  85825. };
  85826. /**
  85827. * Dispose the highlight layer and free resources.
  85828. */
  85829. EffectLayer.prototype.dispose = function () {
  85830. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85831. if (vertexBuffer) {
  85832. vertexBuffer.dispose();
  85833. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85834. }
  85835. if (this._indexBuffer) {
  85836. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85837. this._indexBuffer = null;
  85838. }
  85839. // Clean textures and post processes
  85840. this._disposeTextureAndPostProcesses();
  85841. // Remove from scene
  85842. var index = this._scene.effectLayers.indexOf(this, 0);
  85843. if (index > -1) {
  85844. this._scene.effectLayers.splice(index, 1);
  85845. }
  85846. // Callback
  85847. this.onDisposeObservable.notifyObservers(this);
  85848. this.onDisposeObservable.clear();
  85849. this.onBeforeRenderMainTextureObservable.clear();
  85850. this.onBeforeComposeObservable.clear();
  85851. this.onAfterComposeObservable.clear();
  85852. this.onSizeChangedObservable.clear();
  85853. };
  85854. return EffectLayer;
  85855. }());
  85856. BABYLON.EffectLayer = EffectLayer;
  85857. })(BABYLON || (BABYLON = {}));
  85858. //# sourceMappingURL=babylon.effectLayer.js.map
  85859. "use strict";
  85860. var BABYLON;
  85861. (function (BABYLON) {
  85862. /**
  85863. * Special Glow Blur post process only blurring the alpha channel
  85864. * It enforces keeping the most luminous color in the color channel.
  85865. */
  85866. var GlowBlurPostProcess = /** @class */ (function (_super) {
  85867. __extends(GlowBlurPostProcess, _super);
  85868. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  85869. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85870. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  85871. _this.direction = direction;
  85872. _this.kernel = kernel;
  85873. _this.onApplyObservable.add(function (effect) {
  85874. effect.setFloat2("screenSize", _this.width, _this.height);
  85875. effect.setVector2("direction", _this.direction);
  85876. effect.setFloat("blurWidth", _this.kernel);
  85877. });
  85878. return _this;
  85879. }
  85880. return GlowBlurPostProcess;
  85881. }(BABYLON.PostProcess));
  85882. /**
  85883. * The highlight layer Helps adding a glow effect around a mesh.
  85884. *
  85885. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  85886. * glowy meshes to your scene.
  85887. *
  85888. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  85889. */
  85890. var HighlightLayer = /** @class */ (function (_super) {
  85891. __extends(HighlightLayer, _super);
  85892. /**
  85893. * Instantiates a new highlight Layer and references it to the scene..
  85894. * @param name The name of the layer
  85895. * @param scene The scene to use the layer in
  85896. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  85897. */
  85898. function HighlightLayer(name, scene, options) {
  85899. var _this = _super.call(this, name, scene) || this;
  85900. _this.name = name;
  85901. /**
  85902. * Specifies whether or not the inner glow is ACTIVE in the layer.
  85903. */
  85904. _this.innerGlow = true;
  85905. /**
  85906. * Specifies whether or not the outer glow is ACTIVE in the layer.
  85907. */
  85908. _this.outerGlow = true;
  85909. /**
  85910. * An event triggered when the highlight layer is being blurred.
  85911. */
  85912. _this.onBeforeBlurObservable = new BABYLON.Observable();
  85913. /**
  85914. * An event triggered when the highlight layer has been blurred.
  85915. */
  85916. _this.onAfterBlurObservable = new BABYLON.Observable();
  85917. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  85918. _this._meshes = {};
  85919. _this._excludedMeshes = {};
  85920. _this.neutralColor = HighlightLayer.NeutralColor;
  85921. // Warn on stencil
  85922. if (!_this._engine.isStencilEnable) {
  85923. 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 }");
  85924. }
  85925. // Adapt options
  85926. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  85927. // Initialize the layer
  85928. _this._init({
  85929. alphaBlendingMode: _this._options.alphaBlendingMode,
  85930. camera: _this._options.camera,
  85931. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  85932. mainTextureRatio: _this._options.mainTextureRatio
  85933. });
  85934. // Do not render as long as no meshes have been added
  85935. _this._shouldRender = false;
  85936. return _this;
  85937. }
  85938. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  85939. /**
  85940. * Gets the horizontal size of the blur.
  85941. */
  85942. get: function () {
  85943. return this._horizontalBlurPostprocess.kernel;
  85944. },
  85945. /**
  85946. * Specifies the horizontal size of the blur.
  85947. */
  85948. set: function (value) {
  85949. this._horizontalBlurPostprocess.kernel = value;
  85950. },
  85951. enumerable: true,
  85952. configurable: true
  85953. });
  85954. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  85955. /**
  85956. * Gets the vertical size of the blur.
  85957. */
  85958. get: function () {
  85959. return this._verticalBlurPostprocess.kernel;
  85960. },
  85961. /**
  85962. * Specifies the vertical size of the blur.
  85963. */
  85964. set: function (value) {
  85965. this._verticalBlurPostprocess.kernel = value;
  85966. },
  85967. enumerable: true,
  85968. configurable: true
  85969. });
  85970. /**
  85971. * Get the effect name of the layer.
  85972. * @return The effect name
  85973. */
  85974. HighlightLayer.prototype.getEffectName = function () {
  85975. return HighlightLayer.EffectName;
  85976. };
  85977. /**
  85978. * Create the merge effect. This is the shader use to blit the information back
  85979. * to the main canvas at the end of the scene rendering.
  85980. */
  85981. HighlightLayer.prototype._createMergeEffect = function () {
  85982. // Effect
  85983. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  85984. };
  85985. /**
  85986. * Creates the render target textures and post processes used in the highlight layer.
  85987. */
  85988. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  85989. var _this = this;
  85990. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  85991. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  85992. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  85993. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  85994. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  85995. width: blurTextureWidth,
  85996. height: blurTextureHeight
  85997. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  85998. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85999. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86000. this._blurTexture.anisotropicFilteringLevel = 16;
  86001. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86002. this._blurTexture.renderParticles = false;
  86003. this._blurTexture.ignoreCameraViewport = true;
  86004. this._textures = [this._blurTexture];
  86005. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  86006. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86007. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  86008. effect.setTexture("textureSampler", _this._mainTexture);
  86009. });
  86010. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86011. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86012. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86013. });
  86014. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86015. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  86016. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86017. });
  86018. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86019. }
  86020. else {
  86021. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  86022. width: blurTextureWidth,
  86023. height: blurTextureHeight
  86024. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86025. this._horizontalBlurPostprocess.width = blurTextureWidth;
  86026. this._horizontalBlurPostprocess.height = blurTextureHeight;
  86027. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86028. effect.setTexture("textureSampler", _this._mainTexture);
  86029. });
  86030. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  86031. width: blurTextureWidth,
  86032. height: blurTextureHeight
  86033. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86034. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86035. }
  86036. this._mainTexture.onAfterUnbindObservable.add(function () {
  86037. _this.onBeforeBlurObservable.notifyObservers(_this);
  86038. var internalTexture = _this._blurTexture.getInternalTexture();
  86039. if (internalTexture) {
  86040. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  86041. }
  86042. _this.onAfterBlurObservable.notifyObservers(_this);
  86043. });
  86044. // Prevent autoClear.
  86045. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86046. };
  86047. /**
  86048. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86049. */
  86050. HighlightLayer.prototype.needStencil = function () {
  86051. return true;
  86052. };
  86053. /**
  86054. * Checks for the readiness of the element composing the layer.
  86055. * @param subMesh the mesh to check for
  86056. * @param useInstances specify wether or not to use instances to render the mesh
  86057. * @param emissiveTexture the associated emissive texture used to generate the glow
  86058. * @return true if ready otherwise, false
  86059. */
  86060. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  86061. var material = subMesh.getMaterial();
  86062. var mesh = subMesh.getRenderingMesh();
  86063. if (!material || !mesh || !this._meshes) {
  86064. return false;
  86065. }
  86066. var emissiveTexture = null;
  86067. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86068. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86069. emissiveTexture = material.emissiveTexture;
  86070. }
  86071. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86072. };
  86073. /**
  86074. * Implementation specific of rendering the generating effect on the main canvas.
  86075. * @param effect The effect used to render through
  86076. */
  86077. HighlightLayer.prototype._internalRender = function (effect) {
  86078. // Texture
  86079. effect.setTexture("textureSampler", this._blurTexture);
  86080. // Cache
  86081. var engine = this._engine;
  86082. var previousStencilBuffer = engine.getStencilBuffer();
  86083. var previousStencilFunction = engine.getStencilFunction();
  86084. var previousStencilMask = engine.getStencilMask();
  86085. var previousStencilOperationPass = engine.getStencilOperationPass();
  86086. var previousStencilOperationFail = engine.getStencilOperationFail();
  86087. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  86088. var previousStencilReference = engine.getStencilFunctionReference();
  86089. // Stencil operations
  86090. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  86091. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  86092. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  86093. // Draw order
  86094. engine.setStencilMask(0x00);
  86095. engine.setStencilBuffer(true);
  86096. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  86097. // 2 passes inner outer
  86098. if (this.outerGlow) {
  86099. effect.setFloat("offset", 0);
  86100. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  86101. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86102. }
  86103. if (this.innerGlow) {
  86104. effect.setFloat("offset", 1);
  86105. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  86106. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86107. }
  86108. // Restore Cache
  86109. engine.setStencilFunction(previousStencilFunction);
  86110. engine.setStencilMask(previousStencilMask);
  86111. engine.setStencilBuffer(previousStencilBuffer);
  86112. engine.setStencilOperationPass(previousStencilOperationPass);
  86113. engine.setStencilOperationFail(previousStencilOperationFail);
  86114. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  86115. engine.setStencilFunctionReference(previousStencilReference);
  86116. };
  86117. /**
  86118. * Returns true if the layer contains information to display, otherwise false.
  86119. */
  86120. HighlightLayer.prototype.shouldRender = function () {
  86121. if (_super.prototype.shouldRender.call(this)) {
  86122. return this._meshes ? true : false;
  86123. }
  86124. return false;
  86125. };
  86126. /**
  86127. * Returns true if the mesh should render, otherwise false.
  86128. * @param mesh The mesh to render
  86129. * @returns true if it should render otherwise false
  86130. */
  86131. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  86132. // Excluded Mesh
  86133. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  86134. return false;
  86135. }
  86136. ;
  86137. return true;
  86138. };
  86139. /**
  86140. * Sets the required values for both the emissive texture and and the main color.
  86141. */
  86142. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86143. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86144. if (highlightLayerMesh) {
  86145. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  86146. }
  86147. else {
  86148. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86149. }
  86150. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86151. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86152. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  86153. }
  86154. else {
  86155. this._emissiveTextureAndColor.texture = null;
  86156. }
  86157. };
  86158. /**
  86159. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  86160. * @param mesh The mesh to exclude from the highlight layer
  86161. */
  86162. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  86163. if (!this._excludedMeshes) {
  86164. return;
  86165. }
  86166. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86167. if (!meshExcluded) {
  86168. this._excludedMeshes[mesh.uniqueId] = {
  86169. mesh: mesh,
  86170. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  86171. mesh.getEngine().setStencilBuffer(false);
  86172. }),
  86173. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  86174. mesh.getEngine().setStencilBuffer(true);
  86175. }),
  86176. };
  86177. }
  86178. };
  86179. /**
  86180. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  86181. * @param mesh The mesh to highlight
  86182. */
  86183. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  86184. if (!this._excludedMeshes) {
  86185. return;
  86186. }
  86187. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86188. if (meshExcluded) {
  86189. if (meshExcluded.beforeRender) {
  86190. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86191. }
  86192. if (meshExcluded.afterRender) {
  86193. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86194. }
  86195. }
  86196. this._excludedMeshes[mesh.uniqueId] = null;
  86197. };
  86198. /**
  86199. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86200. * @param mesh mesh to test
  86201. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86202. */
  86203. HighlightLayer.prototype.hasMesh = function (mesh) {
  86204. if (!this._meshes) {
  86205. return false;
  86206. }
  86207. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  86208. };
  86209. /**
  86210. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  86211. * @param mesh The mesh to highlight
  86212. * @param color The color of the highlight
  86213. * @param glowEmissiveOnly Extract the glow from the emissive texture
  86214. */
  86215. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  86216. var _this = this;
  86217. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  86218. if (!this._meshes) {
  86219. return;
  86220. }
  86221. var meshHighlight = this._meshes[mesh.uniqueId];
  86222. if (meshHighlight) {
  86223. meshHighlight.color = color;
  86224. }
  86225. else {
  86226. this._meshes[mesh.uniqueId] = {
  86227. mesh: mesh,
  86228. color: color,
  86229. // Lambda required for capture due to Observable this context
  86230. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  86231. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  86232. _this._defaultStencilReference(mesh);
  86233. }
  86234. else {
  86235. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  86236. }
  86237. }),
  86238. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  86239. glowEmissiveOnly: glowEmissiveOnly
  86240. };
  86241. }
  86242. this._shouldRender = true;
  86243. };
  86244. /**
  86245. * Remove a mesh from the highlight layer in order to make it stop glowing.
  86246. * @param mesh The mesh to highlight
  86247. */
  86248. HighlightLayer.prototype.removeMesh = function (mesh) {
  86249. if (!this._meshes) {
  86250. return;
  86251. }
  86252. var meshHighlight = this._meshes[mesh.uniqueId];
  86253. if (meshHighlight) {
  86254. if (meshHighlight.observerHighlight) {
  86255. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86256. }
  86257. if (meshHighlight.observerDefault) {
  86258. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86259. }
  86260. delete this._meshes[mesh.uniqueId];
  86261. }
  86262. this._shouldRender = false;
  86263. for (var meshHighlightToCheck in this._meshes) {
  86264. if (this._meshes[meshHighlightToCheck]) {
  86265. this._shouldRender = true;
  86266. break;
  86267. }
  86268. }
  86269. };
  86270. /**
  86271. * Force the stencil to the normal expected value for none glowing parts
  86272. */
  86273. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  86274. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  86275. };
  86276. /**
  86277. * Free any resources and references associated to a mesh.
  86278. * Internal use
  86279. * @param mesh The mesh to free.
  86280. */
  86281. HighlightLayer.prototype._disposeMesh = function (mesh) {
  86282. this.removeMesh(mesh);
  86283. this.removeExcludedMesh(mesh);
  86284. };
  86285. /**
  86286. * Dispose the highlight layer and free resources.
  86287. */
  86288. HighlightLayer.prototype.dispose = function () {
  86289. if (this._meshes) {
  86290. // Clean mesh references
  86291. for (var id in this._meshes) {
  86292. var meshHighlight = this._meshes[id];
  86293. if (meshHighlight && meshHighlight.mesh) {
  86294. if (meshHighlight.observerHighlight) {
  86295. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86296. }
  86297. if (meshHighlight.observerDefault) {
  86298. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86299. }
  86300. }
  86301. }
  86302. this._meshes = null;
  86303. }
  86304. if (this._excludedMeshes) {
  86305. for (var id in this._excludedMeshes) {
  86306. var meshHighlight = this._excludedMeshes[id];
  86307. if (meshHighlight) {
  86308. if (meshHighlight.beforeRender) {
  86309. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  86310. }
  86311. if (meshHighlight.afterRender) {
  86312. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  86313. }
  86314. }
  86315. }
  86316. this._excludedMeshes = null;
  86317. }
  86318. _super.prototype.dispose.call(this);
  86319. };
  86320. /**
  86321. * Effect Name of the highlight layer.
  86322. */
  86323. HighlightLayer.EffectName = "HighlightLayer";
  86324. /**
  86325. * The neutral color used during the preparation of the glow effect.
  86326. * This is black by default as the blend operation is a blend operation.
  86327. */
  86328. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  86329. /**
  86330. * Stencil value used for glowing meshes.
  86331. */
  86332. HighlightLayer.GlowingMeshStencilReference = 0x02;
  86333. /**
  86334. * Stencil value used for the other meshes in the scene.
  86335. */
  86336. HighlightLayer.NormalMeshStencilReference = 0x01;
  86337. return HighlightLayer;
  86338. }(BABYLON.EffectLayer));
  86339. BABYLON.HighlightLayer = HighlightLayer;
  86340. })(BABYLON || (BABYLON = {}));
  86341. //# sourceMappingURL=babylon.highlightLayer.js.map
  86342. "use strict";
  86343. var BABYLON;
  86344. (function (BABYLON) {
  86345. /**
  86346. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  86347. *
  86348. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86349. * glowy meshes to your scene.
  86350. *
  86351. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  86352. */
  86353. var GlowLayer = /** @class */ (function (_super) {
  86354. __extends(GlowLayer, _super);
  86355. /**
  86356. * Instantiates a new glow Layer and references it to the scene.
  86357. * @param name The name of the layer
  86358. * @param scene The scene to use the layer in
  86359. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  86360. */
  86361. function GlowLayer(name, scene, options) {
  86362. var _this = _super.call(this, name, scene) || this;
  86363. _this.name = name;
  86364. _this._intensity = 1.0;
  86365. _this._includedOnlyMeshes = [];
  86366. _this._excludedMeshes = [];
  86367. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  86368. // Adapt options
  86369. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  86370. // Initialize the layer
  86371. _this._init({
  86372. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  86373. camera: _this._options.camera,
  86374. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86375. mainTextureRatio: _this._options.mainTextureRatio
  86376. });
  86377. return _this;
  86378. }
  86379. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  86380. /**
  86381. * Gets the kernel size of the blur.
  86382. */
  86383. get: function () {
  86384. return this._horizontalBlurPostprocess1.kernel;
  86385. },
  86386. /**
  86387. * Sets the kernel size of the blur.
  86388. */
  86389. set: function (value) {
  86390. this._horizontalBlurPostprocess1.kernel = value;
  86391. this._verticalBlurPostprocess1.kernel = value;
  86392. this._horizontalBlurPostprocess2.kernel = value;
  86393. this._verticalBlurPostprocess2.kernel = value;
  86394. },
  86395. enumerable: true,
  86396. configurable: true
  86397. });
  86398. Object.defineProperty(GlowLayer.prototype, "intensity", {
  86399. /**
  86400. * Gets the glow intensity.
  86401. */
  86402. get: function () {
  86403. return this._intensity;
  86404. },
  86405. /**
  86406. * Sets the glow intensity.
  86407. */
  86408. set: function (value) {
  86409. this._intensity = value;
  86410. },
  86411. enumerable: true,
  86412. configurable: true
  86413. });
  86414. /**
  86415. * Get the effect name of the layer.
  86416. * @return The effect name
  86417. */
  86418. GlowLayer.prototype.getEffectName = function () {
  86419. return GlowLayer.EffectName;
  86420. };
  86421. /**
  86422. * Create the merge effect. This is the shader use to blit the information back
  86423. * to the main canvas at the end of the scene rendering.
  86424. */
  86425. GlowLayer.prototype._createMergeEffect = function () {
  86426. // Effect
  86427. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  86428. };
  86429. /**
  86430. * Creates the render target textures and post processes used in the glow layer.
  86431. */
  86432. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  86433. var _this = this;
  86434. var blurTextureWidth = this._mainTextureDesiredSize.width;
  86435. var blurTextureHeight = this._mainTextureDesiredSize.height;
  86436. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86437. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86438. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  86439. width: blurTextureWidth,
  86440. height: blurTextureHeight
  86441. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86442. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86443. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86444. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86445. this._blurTexture1.renderParticles = false;
  86446. this._blurTexture1.ignoreCameraViewport = true;
  86447. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  86448. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  86449. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  86450. width: blurTextureWidth2,
  86451. height: blurTextureHeight2
  86452. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86453. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86454. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86455. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86456. this._blurTexture2.renderParticles = false;
  86457. this._blurTexture2.ignoreCameraViewport = true;
  86458. this._textures = [this._blurTexture1, this._blurTexture2];
  86459. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86460. width: blurTextureWidth,
  86461. height: blurTextureHeight
  86462. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86463. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  86464. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  86465. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  86466. effect.setTexture("textureSampler", _this._mainTexture);
  86467. });
  86468. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86469. width: blurTextureWidth,
  86470. height: blurTextureHeight
  86471. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86472. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  86473. width: blurTextureWidth2,
  86474. height: blurTextureHeight2
  86475. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86476. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  86477. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  86478. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  86479. effect.setTexture("textureSampler", _this._blurTexture1);
  86480. });
  86481. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  86482. width: blurTextureWidth2,
  86483. height: blurTextureHeight2
  86484. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86485. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86486. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  86487. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  86488. this._mainTexture.samples = this._options.mainTextureSamples;
  86489. this._mainTexture.onAfterUnbindObservable.add(function () {
  86490. var internalTexture = _this._blurTexture1.getInternalTexture();
  86491. if (internalTexture) {
  86492. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  86493. internalTexture = _this._blurTexture2.getInternalTexture();
  86494. if (internalTexture) {
  86495. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  86496. }
  86497. }
  86498. });
  86499. // Prevent autoClear.
  86500. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86501. };
  86502. /**
  86503. * Checks for the readiness of the element composing the layer.
  86504. * @param subMesh the mesh to check for
  86505. * @param useInstances specify wether or not to use instances to render the mesh
  86506. * @param emissiveTexture the associated emissive texture used to generate the glow
  86507. * @return true if ready otherwise, false
  86508. */
  86509. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  86510. var material = subMesh.getMaterial();
  86511. var mesh = subMesh.getRenderingMesh();
  86512. if (!material || !mesh) {
  86513. return false;
  86514. }
  86515. var emissiveTexture = material.emissiveTexture;
  86516. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86517. };
  86518. /**
  86519. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86520. */
  86521. GlowLayer.prototype.needStencil = function () {
  86522. return false;
  86523. };
  86524. /**
  86525. * Implementation specific of rendering the generating effect on the main canvas.
  86526. * @param effect The effect used to render through
  86527. */
  86528. GlowLayer.prototype._internalRender = function (effect) {
  86529. // Texture
  86530. effect.setTexture("textureSampler", this._blurTexture1);
  86531. effect.setTexture("textureSampler2", this._blurTexture2);
  86532. effect.setFloat("offset", this._intensity);
  86533. // Cache
  86534. var engine = this._engine;
  86535. var previousStencilBuffer = engine.getStencilBuffer();
  86536. // Draw order
  86537. engine.setStencilBuffer(false);
  86538. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86539. // Draw order
  86540. engine.setStencilBuffer(previousStencilBuffer);
  86541. };
  86542. /**
  86543. * Sets the required values for both the emissive texture and and the main color.
  86544. */
  86545. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86546. var textureLevel = 1.0;
  86547. if (this.customEmissiveTextureSelector) {
  86548. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  86549. }
  86550. else {
  86551. if (material) {
  86552. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86553. if (this._emissiveTextureAndColor.texture) {
  86554. textureLevel = this._emissiveTextureAndColor.texture.level;
  86555. }
  86556. }
  86557. else {
  86558. this._emissiveTextureAndColor.texture = null;
  86559. }
  86560. }
  86561. if (this.customEmissiveColorSelector) {
  86562. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  86563. }
  86564. else {
  86565. if (material.emissiveColor) {
  86566. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  86567. }
  86568. else {
  86569. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86570. }
  86571. }
  86572. };
  86573. /**
  86574. * Returns true if the mesh should render, otherwise false.
  86575. * @param mesh The mesh to render
  86576. * @returns true if it should render otherwise false
  86577. */
  86578. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  86579. return this.hasMesh(mesh);
  86580. };
  86581. /**
  86582. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  86583. * @param mesh The mesh to exclude from the glow layer
  86584. */
  86585. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  86586. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  86587. this._excludedMeshes.push(mesh.uniqueId);
  86588. }
  86589. };
  86590. /**
  86591. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  86592. * @param mesh The mesh to remove
  86593. */
  86594. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  86595. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  86596. if (index !== -1) {
  86597. this._excludedMeshes.splice(index, 1);
  86598. }
  86599. };
  86600. /**
  86601. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  86602. * @param mesh The mesh to include in the glow layer
  86603. */
  86604. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  86605. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  86606. this._includedOnlyMeshes.push(mesh.uniqueId);
  86607. }
  86608. };
  86609. /**
  86610. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  86611. * @param mesh The mesh to remove
  86612. */
  86613. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  86614. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  86615. if (index !== -1) {
  86616. this._includedOnlyMeshes.splice(index, 1);
  86617. }
  86618. };
  86619. /**
  86620. * Determine if a given mesh will be used in the glow layer
  86621. * @param mesh The mesh to test
  86622. * @returns true if the mesh will be highlighted by the current glow layer
  86623. */
  86624. GlowLayer.prototype.hasMesh = function (mesh) {
  86625. // Included Mesh
  86626. if (this._includedOnlyMeshes.length) {
  86627. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  86628. }
  86629. ;
  86630. // Excluded Mesh
  86631. if (this._excludedMeshes.length) {
  86632. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  86633. }
  86634. ;
  86635. return true;
  86636. };
  86637. /**
  86638. * Free any resources and references associated to a mesh.
  86639. * Internal use
  86640. * @param mesh The mesh to free.
  86641. */
  86642. GlowLayer.prototype._disposeMesh = function (mesh) {
  86643. this.removeIncludedOnlyMesh(mesh);
  86644. this.removeExcludedMesh(mesh);
  86645. };
  86646. /**
  86647. * Effect Name of the layer.
  86648. */
  86649. GlowLayer.EffectName = "GlowLayer";
  86650. /**
  86651. * The default blur kernel size used for the glow.
  86652. */
  86653. GlowLayer.DefaultBlurKernelSize = 32;
  86654. /**
  86655. * The default texture size ratio used for the glow.
  86656. */
  86657. GlowLayer.DefaultTextureRatio = 0.5;
  86658. return GlowLayer;
  86659. }(BABYLON.EffectLayer));
  86660. BABYLON.GlowLayer = GlowLayer;
  86661. })(BABYLON || (BABYLON = {}));
  86662. //# sourceMappingURL=babylon.glowLayer.js.map
  86663. "use strict";
  86664. var BABYLON;
  86665. (function (BABYLON) {
  86666. /**
  86667. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  86668. */
  86669. var AssetTaskState;
  86670. (function (AssetTaskState) {
  86671. /**
  86672. * Initialization
  86673. */
  86674. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  86675. /**
  86676. * Running
  86677. */
  86678. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  86679. /**
  86680. * Done
  86681. */
  86682. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  86683. /**
  86684. * Error
  86685. */
  86686. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  86687. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  86688. /**
  86689. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  86690. */
  86691. var AbstractAssetTask = /** @class */ (function () {
  86692. /**
  86693. * Creates a new {BABYLON.AssetsManager}
  86694. * @param name defines the name of the task
  86695. */
  86696. function AbstractAssetTask(
  86697. /**
  86698. * Task name
  86699. */ name) {
  86700. this.name = name;
  86701. this._isCompleted = false;
  86702. this._taskState = AssetTaskState.INIT;
  86703. }
  86704. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  86705. /**
  86706. * Get if the task is completed
  86707. */
  86708. get: function () {
  86709. return this._isCompleted;
  86710. },
  86711. enumerable: true,
  86712. configurable: true
  86713. });
  86714. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  86715. /**
  86716. * Gets the current state of the task
  86717. */
  86718. get: function () {
  86719. return this._taskState;
  86720. },
  86721. enumerable: true,
  86722. configurable: true
  86723. });
  86724. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  86725. /**
  86726. * Gets the current error object (if task is in error)
  86727. */
  86728. get: function () {
  86729. return this._errorObject;
  86730. },
  86731. enumerable: true,
  86732. configurable: true
  86733. });
  86734. /**
  86735. * Internal only
  86736. * @ignore
  86737. */
  86738. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  86739. if (this._errorObject) {
  86740. return;
  86741. }
  86742. this._errorObject = {
  86743. message: message,
  86744. exception: exception
  86745. };
  86746. };
  86747. /**
  86748. * Execute the current task
  86749. * @param scene defines the scene where you want your assets to be loaded
  86750. * @param onSuccess is a callback called when the task is successfully executed
  86751. * @param onError is a callback called if an error occurs
  86752. */
  86753. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  86754. var _this = this;
  86755. this._taskState = AssetTaskState.RUNNING;
  86756. this.runTask(scene, function () {
  86757. _this.onDoneCallback(onSuccess, onError);
  86758. }, function (msg, exception) {
  86759. _this.onErrorCallback(onError, msg, exception);
  86760. });
  86761. };
  86762. /**
  86763. * Execute the current task
  86764. * @param scene defines the scene where you want your assets to be loaded
  86765. * @param onSuccess is a callback called when the task is successfully executed
  86766. * @param onError is a callback called if an error occurs
  86767. */
  86768. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86769. throw new Error("runTask is not implemented");
  86770. };
  86771. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  86772. this._taskState = AssetTaskState.ERROR;
  86773. this._errorObject = {
  86774. message: message,
  86775. exception: exception
  86776. };
  86777. if (this.onError) {
  86778. this.onError(this, message, exception);
  86779. }
  86780. onError();
  86781. };
  86782. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  86783. try {
  86784. this._taskState = AssetTaskState.DONE;
  86785. this._isCompleted = true;
  86786. if (this.onSuccess) {
  86787. this.onSuccess(this);
  86788. }
  86789. onSuccess();
  86790. }
  86791. catch (e) {
  86792. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  86793. }
  86794. };
  86795. return AbstractAssetTask;
  86796. }());
  86797. BABYLON.AbstractAssetTask = AbstractAssetTask;
  86798. /**
  86799. * Class used to share progress information about assets loading
  86800. */
  86801. var AssetsProgressEvent = /** @class */ (function () {
  86802. /**
  86803. * Creates a {BABYLON.AssetsProgressEvent}
  86804. * @param remainingCount defines the number of remaining tasks to process
  86805. * @param totalCount defines the total number of tasks
  86806. * @param task defines the task that was just processed
  86807. */
  86808. function AssetsProgressEvent(remainingCount, totalCount, task) {
  86809. this.remainingCount = remainingCount;
  86810. this.totalCount = totalCount;
  86811. this.task = task;
  86812. }
  86813. return AssetsProgressEvent;
  86814. }());
  86815. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  86816. /**
  86817. * Define a task used by {BABYLON.AssetsManager} to load meshes
  86818. */
  86819. var MeshAssetTask = /** @class */ (function (_super) {
  86820. __extends(MeshAssetTask, _super);
  86821. /**
  86822. * Creates a new {BABYLON.MeshAssetTask}
  86823. * @param name defines the name of the task
  86824. * @param meshesNames defines the list of mesh's names you want to load
  86825. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  86826. * @param sceneFilename defines the filename of the scene to load from
  86827. */
  86828. function MeshAssetTask(
  86829. /**
  86830. * Defines the name of the task
  86831. */
  86832. name,
  86833. /**
  86834. * Defines the list of mesh's names you want to load
  86835. */
  86836. meshesNames,
  86837. /**
  86838. * Defines the root url to use as a base to load your meshes and associated resources
  86839. */
  86840. rootUrl,
  86841. /**
  86842. * Defines the filename of the scene to load from
  86843. */
  86844. sceneFilename) {
  86845. var _this = _super.call(this, name) || this;
  86846. _this.name = name;
  86847. _this.meshesNames = meshesNames;
  86848. _this.rootUrl = rootUrl;
  86849. _this.sceneFilename = sceneFilename;
  86850. return _this;
  86851. }
  86852. /**
  86853. * Execute the current task
  86854. * @param scene defines the scene where you want your assets to be loaded
  86855. * @param onSuccess is a callback called when the task is successfully executed
  86856. * @param onError is a callback called if an error occurs
  86857. */
  86858. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86859. var _this = this;
  86860. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  86861. _this.loadedMeshes = meshes;
  86862. _this.loadedParticleSystems = particleSystems;
  86863. _this.loadedSkeletons = skeletons;
  86864. onSuccess();
  86865. }, null, function (scene, message, exception) {
  86866. onError(message, exception);
  86867. });
  86868. };
  86869. return MeshAssetTask;
  86870. }(AbstractAssetTask));
  86871. BABYLON.MeshAssetTask = MeshAssetTask;
  86872. /**
  86873. * Define a task used by {BABYLON.AssetsManager} to load text content
  86874. */
  86875. var TextFileAssetTask = /** @class */ (function (_super) {
  86876. __extends(TextFileAssetTask, _super);
  86877. /**
  86878. * Creates a new TextFileAssetTask object
  86879. * @param name defines the name of the task
  86880. * @param url defines the location of the file to load
  86881. */
  86882. function TextFileAssetTask(
  86883. /**
  86884. * Defines the name of the task
  86885. */
  86886. name,
  86887. /**
  86888. * Defines the location of the file to load
  86889. */
  86890. url) {
  86891. var _this = _super.call(this, name) || this;
  86892. _this.name = name;
  86893. _this.url = url;
  86894. return _this;
  86895. }
  86896. /**
  86897. * Execute the current task
  86898. * @param scene defines the scene where you want your assets to be loaded
  86899. * @param onSuccess is a callback called when the task is successfully executed
  86900. * @param onError is a callback called if an error occurs
  86901. */
  86902. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86903. var _this = this;
  86904. scene._loadFile(this.url, function (data) {
  86905. _this.text = data;
  86906. onSuccess();
  86907. }, undefined, false, false, function (request, exception) {
  86908. if (request) {
  86909. onError(request.status + " " + request.statusText, exception);
  86910. }
  86911. });
  86912. };
  86913. return TextFileAssetTask;
  86914. }(AbstractAssetTask));
  86915. BABYLON.TextFileAssetTask = TextFileAssetTask;
  86916. /**
  86917. * Define a task used by {BABYLON.AssetsManager} to load binary data
  86918. */
  86919. var BinaryFileAssetTask = /** @class */ (function (_super) {
  86920. __extends(BinaryFileAssetTask, _super);
  86921. /**
  86922. * Creates a new BinaryFileAssetTask object
  86923. * @param name defines the name of the new task
  86924. * @param url defines the location of the file to load
  86925. */
  86926. function BinaryFileAssetTask(
  86927. /**
  86928. * Defines the name of the task
  86929. */
  86930. name,
  86931. /**
  86932. * Defines the location of the file to load
  86933. */
  86934. url) {
  86935. var _this = _super.call(this, name) || this;
  86936. _this.name = name;
  86937. _this.url = url;
  86938. return _this;
  86939. }
  86940. /**
  86941. * Execute the current task
  86942. * @param scene defines the scene where you want your assets to be loaded
  86943. * @param onSuccess is a callback called when the task is successfully executed
  86944. * @param onError is a callback called if an error occurs
  86945. */
  86946. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86947. var _this = this;
  86948. scene._loadFile(this.url, function (data) {
  86949. _this.data = data;
  86950. onSuccess();
  86951. }, undefined, true, true, function (request, exception) {
  86952. if (request) {
  86953. onError(request.status + " " + request.statusText, exception);
  86954. }
  86955. });
  86956. };
  86957. return BinaryFileAssetTask;
  86958. }(AbstractAssetTask));
  86959. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  86960. /**
  86961. * Define a task used by {BABYLON.AssetsManager} to load images
  86962. */
  86963. var ImageAssetTask = /** @class */ (function (_super) {
  86964. __extends(ImageAssetTask, _super);
  86965. /**
  86966. * Creates a new ImageAssetTask
  86967. * @param name defines the name of the task
  86968. * @param url defines the location of the image to load
  86969. */
  86970. function ImageAssetTask(
  86971. /**
  86972. * Defines the name of the task
  86973. */
  86974. name,
  86975. /**
  86976. * Defines the location of the image to load
  86977. */
  86978. url) {
  86979. var _this = _super.call(this, name) || this;
  86980. _this.name = name;
  86981. _this.url = url;
  86982. return _this;
  86983. }
  86984. /**
  86985. * Execute the current task
  86986. * @param scene defines the scene where you want your assets to be loaded
  86987. * @param onSuccess is a callback called when the task is successfully executed
  86988. * @param onError is a callback called if an error occurs
  86989. */
  86990. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  86991. var _this = this;
  86992. var img = new Image();
  86993. BABYLON.Tools.SetCorsBehavior(this.url, img);
  86994. img.onload = function () {
  86995. _this.image = img;
  86996. onSuccess();
  86997. };
  86998. img.onerror = function (err) {
  86999. onError("Error loading image", err);
  87000. };
  87001. img.src = this.url;
  87002. };
  87003. return ImageAssetTask;
  87004. }(AbstractAssetTask));
  87005. BABYLON.ImageAssetTask = ImageAssetTask;
  87006. /**
  87007. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  87008. */
  87009. var TextureAssetTask = /** @class */ (function (_super) {
  87010. __extends(TextureAssetTask, _super);
  87011. /**
  87012. * Creates a new TextureAssetTask object
  87013. * @param name defines the name of the task
  87014. * @param url defines the location of the file to load
  87015. * @param noMipmap defines if mipmap should not be generated (default is false)
  87016. * @param invertY defines if texture must be inverted on Y axis (default is false)
  87017. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87018. */
  87019. function TextureAssetTask(
  87020. /**
  87021. * Defines the name of the task
  87022. */
  87023. name,
  87024. /**
  87025. * Defines the location of the file to load
  87026. */
  87027. url,
  87028. /**
  87029. * Defines if mipmap should not be generated (default is false)
  87030. */
  87031. noMipmap,
  87032. /**
  87033. * Defines if texture must be inverted on Y axis (default is false)
  87034. */
  87035. invertY,
  87036. /**
  87037. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87038. */
  87039. samplingMode) {
  87040. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87041. var _this = _super.call(this, name) || this;
  87042. _this.name = name;
  87043. _this.url = url;
  87044. _this.noMipmap = noMipmap;
  87045. _this.invertY = invertY;
  87046. _this.samplingMode = samplingMode;
  87047. return _this;
  87048. }
  87049. /**
  87050. * Execute the current task
  87051. * @param scene defines the scene where you want your assets to be loaded
  87052. * @param onSuccess is a callback called when the task is successfully executed
  87053. * @param onError is a callback called if an error occurs
  87054. */
  87055. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87056. var onload = function () {
  87057. onSuccess();
  87058. };
  87059. var onerror = function (message, exception) {
  87060. onError(message, exception);
  87061. };
  87062. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  87063. };
  87064. return TextureAssetTask;
  87065. }(AbstractAssetTask));
  87066. BABYLON.TextureAssetTask = TextureAssetTask;
  87067. /**
  87068. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  87069. */
  87070. var CubeTextureAssetTask = /** @class */ (function (_super) {
  87071. __extends(CubeTextureAssetTask, _super);
  87072. /**
  87073. * Creates a new CubeTextureAssetTask
  87074. * @param name defines the name of the task
  87075. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87076. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87077. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87078. * @param files defines the explicit list of files (undefined by default)
  87079. */
  87080. function CubeTextureAssetTask(
  87081. /**
  87082. * Defines the name of the task
  87083. */
  87084. name,
  87085. /**
  87086. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87087. */
  87088. url,
  87089. /**
  87090. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87091. */
  87092. extensions,
  87093. /**
  87094. * Defines if mipmaps should not be generated (default is false)
  87095. */
  87096. noMipmap,
  87097. /**
  87098. * Defines the explicit list of files (undefined by default)
  87099. */
  87100. files) {
  87101. var _this = _super.call(this, name) || this;
  87102. _this.name = name;
  87103. _this.url = url;
  87104. _this.extensions = extensions;
  87105. _this.noMipmap = noMipmap;
  87106. _this.files = files;
  87107. return _this;
  87108. }
  87109. /**
  87110. * Execute the current task
  87111. * @param scene defines the scene where you want your assets to be loaded
  87112. * @param onSuccess is a callback called when the task is successfully executed
  87113. * @param onError is a callback called if an error occurs
  87114. */
  87115. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87116. var onload = function () {
  87117. onSuccess();
  87118. };
  87119. var onerror = function (message, exception) {
  87120. onError(message, exception);
  87121. };
  87122. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  87123. };
  87124. return CubeTextureAssetTask;
  87125. }(AbstractAssetTask));
  87126. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  87127. /**
  87128. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  87129. */
  87130. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  87131. __extends(HDRCubeTextureAssetTask, _super);
  87132. /**
  87133. * Creates a new HDRCubeTextureAssetTask object
  87134. * @param name defines the name of the task
  87135. * @param url defines the location of the file to load
  87136. * @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.
  87137. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87138. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87139. * @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)
  87140. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87141. */
  87142. function HDRCubeTextureAssetTask(
  87143. /**
  87144. * Defines the name of the task
  87145. */
  87146. name,
  87147. /**
  87148. * Defines the location of the file to load
  87149. */
  87150. url,
  87151. /**
  87152. * 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.
  87153. */
  87154. size,
  87155. /**
  87156. * Defines if mipmaps should not be generated (default is false)
  87157. */
  87158. noMipmap,
  87159. /**
  87160. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87161. */
  87162. generateHarmonics,
  87163. /**
  87164. * 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)
  87165. */
  87166. useInGammaSpace,
  87167. /**
  87168. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87169. */
  87170. usePMREMGenerator) {
  87171. if (noMipmap === void 0) { noMipmap = false; }
  87172. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87173. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87174. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87175. var _this = _super.call(this, name) || this;
  87176. _this.name = name;
  87177. _this.url = url;
  87178. _this.size = size;
  87179. _this.noMipmap = noMipmap;
  87180. _this.generateHarmonics = generateHarmonics;
  87181. _this.useInGammaSpace = useInGammaSpace;
  87182. _this.usePMREMGenerator = usePMREMGenerator;
  87183. return _this;
  87184. }
  87185. /**
  87186. * Execute the current task
  87187. * @param scene defines the scene where you want your assets to be loaded
  87188. * @param onSuccess is a callback called when the task is successfully executed
  87189. * @param onError is a callback called if an error occurs
  87190. */
  87191. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87192. var onload = function () {
  87193. onSuccess();
  87194. };
  87195. var onerror = function (message, exception) {
  87196. onError(message, exception);
  87197. };
  87198. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87199. };
  87200. return HDRCubeTextureAssetTask;
  87201. }(AbstractAssetTask));
  87202. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87203. /**
  87204. * This class can be used to easily import assets into a scene
  87205. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  87206. */
  87207. var AssetsManager = /** @class */ (function () {
  87208. /**
  87209. * Creates a new AssetsManager
  87210. * @param scene defines the scene to work on
  87211. */
  87212. function AssetsManager(scene) {
  87213. this._isLoading = false;
  87214. this._tasks = new Array();
  87215. this._waitingTasksCount = 0;
  87216. this._totalTasksCount = 0;
  87217. /**
  87218. * Observable called when all tasks are processed
  87219. */
  87220. this.onTaskSuccessObservable = new BABYLON.Observable();
  87221. /**
  87222. * Observable called when a task had an error
  87223. */
  87224. this.onTaskErrorObservable = new BABYLON.Observable();
  87225. /**
  87226. * Observable called when a task is successful
  87227. */
  87228. this.onTasksDoneObservable = new BABYLON.Observable();
  87229. /**
  87230. * Observable called when a task is done (whatever the result is)
  87231. */
  87232. this.onProgressObservable = new BABYLON.Observable();
  87233. /**
  87234. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  87235. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  87236. */
  87237. this.useDefaultLoadingScreen = true;
  87238. this._scene = scene;
  87239. }
  87240. /**
  87241. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  87242. * @param taskName defines the name of the new task
  87243. * @param meshesNames defines the name of meshes to load
  87244. * @param rootUrl defines the root url to use to locate files
  87245. * @param sceneFilename defines the filename of the scene file
  87246. * @returns a new {BABYLON.MeshAssetTask} object
  87247. */
  87248. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  87249. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  87250. this._tasks.push(task);
  87251. return task;
  87252. };
  87253. /**
  87254. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  87255. * @param taskName defines the name of the new task
  87256. * @param url defines the url of the file to load
  87257. * @returns a new {BABYLON.TextFileAssetTask} object
  87258. */
  87259. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  87260. var task = new TextFileAssetTask(taskName, url);
  87261. this._tasks.push(task);
  87262. return task;
  87263. };
  87264. /**
  87265. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  87266. * @param taskName defines the name of the new task
  87267. * @param url defines the url of the file to load
  87268. * @returns a new {BABYLON.BinaryFileAssetTask} object
  87269. */
  87270. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  87271. var task = new BinaryFileAssetTask(taskName, url);
  87272. this._tasks.push(task);
  87273. return task;
  87274. };
  87275. /**
  87276. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  87277. * @param taskName defines the name of the new task
  87278. * @param url defines the url of the file to load
  87279. * @returns a new {BABYLON.ImageAssetTask} object
  87280. */
  87281. AssetsManager.prototype.addImageTask = function (taskName, url) {
  87282. var task = new ImageAssetTask(taskName, url);
  87283. this._tasks.push(task);
  87284. return task;
  87285. };
  87286. /**
  87287. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  87288. * @param taskName defines the name of the new task
  87289. * @param url defines the url of the file to load
  87290. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87291. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  87292. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  87293. * @returns a new {BABYLON.TextureAssetTask} object
  87294. */
  87295. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  87296. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87297. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  87298. this._tasks.push(task);
  87299. return task;
  87300. };
  87301. /**
  87302. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  87303. * @param taskName defines the name of the new task
  87304. * @param url defines the url of the file to load
  87305. * @param extensions defines the extension to use to load the cube map (can be null)
  87306. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87307. * @param files defines the list of files to load (can be null)
  87308. * @returns a new {BABYLON.CubeTextureAssetTask} object
  87309. */
  87310. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  87311. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  87312. this._tasks.push(task);
  87313. return task;
  87314. };
  87315. /**
  87316. *
  87317. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  87318. * @param taskName defines the name of the new task
  87319. * @param url defines the url of the file to load
  87320. * @param size defines the size you want for the cubemap (can be null)
  87321. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87322. * @param generateHarmonics defines if you want to automatically generate (true by default)
  87323. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  87324. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  87325. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  87326. */
  87327. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  87328. if (noMipmap === void 0) { noMipmap = false; }
  87329. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87330. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87331. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87332. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  87333. this._tasks.push(task);
  87334. return task;
  87335. };
  87336. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  87337. var _this = this;
  87338. this._waitingTasksCount--;
  87339. try {
  87340. if (task.taskState === AssetTaskState.DONE) {
  87341. // Let's remove successfull tasks
  87342. BABYLON.Tools.SetImmediate(function () {
  87343. var index = _this._tasks.indexOf(task);
  87344. if (index > -1) {
  87345. _this._tasks.splice(index, 1);
  87346. }
  87347. });
  87348. }
  87349. if (this.onProgress) {
  87350. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  87351. }
  87352. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  87353. }
  87354. catch (e) {
  87355. BABYLON.Tools.Error("Error running progress callbacks.");
  87356. console.log(e);
  87357. }
  87358. if (this._waitingTasksCount === 0) {
  87359. try {
  87360. if (this.onFinish) {
  87361. this.onFinish(this._tasks);
  87362. }
  87363. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87364. }
  87365. catch (e) {
  87366. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  87367. console.log(e);
  87368. }
  87369. this._isLoading = false;
  87370. this._scene.getEngine().hideLoadingUI();
  87371. }
  87372. };
  87373. AssetsManager.prototype._runTask = function (task) {
  87374. var _this = this;
  87375. var done = function () {
  87376. try {
  87377. if (_this.onTaskSuccess) {
  87378. _this.onTaskSuccess(task);
  87379. }
  87380. _this.onTaskSuccessObservable.notifyObservers(task);
  87381. _this._decreaseWaitingTasksCount(task);
  87382. }
  87383. catch (e) {
  87384. error("Error executing task success callbacks", e);
  87385. }
  87386. };
  87387. var error = function (message, exception) {
  87388. task._setErrorObject(message, exception);
  87389. if (_this.onTaskError) {
  87390. _this.onTaskError(task);
  87391. }
  87392. _this.onTaskErrorObservable.notifyObservers(task);
  87393. _this._decreaseWaitingTasksCount(task);
  87394. };
  87395. task.run(this._scene, done, error);
  87396. };
  87397. /**
  87398. * Reset the {BABYLON.AssetsManager} and remove all tasks
  87399. * @return the current instance of the {BABYLON.AssetsManager}
  87400. */
  87401. AssetsManager.prototype.reset = function () {
  87402. this._isLoading = false;
  87403. this._tasks = new Array();
  87404. return this;
  87405. };
  87406. /**
  87407. * Start the loading process
  87408. * @return the current instance of the {BABYLON.AssetsManager}
  87409. */
  87410. AssetsManager.prototype.load = function () {
  87411. if (this._isLoading) {
  87412. return this;
  87413. }
  87414. this._isLoading = true;
  87415. this._waitingTasksCount = this._tasks.length;
  87416. this._totalTasksCount = this._tasks.length;
  87417. if (this._waitingTasksCount === 0) {
  87418. this._isLoading = false;
  87419. if (this.onFinish) {
  87420. this.onFinish(this._tasks);
  87421. }
  87422. this.onTasksDoneObservable.notifyObservers(this._tasks);
  87423. return this;
  87424. }
  87425. if (this.useDefaultLoadingScreen) {
  87426. this._scene.getEngine().displayLoadingUI();
  87427. }
  87428. for (var index = 0; index < this._tasks.length; index++) {
  87429. var task = this._tasks[index];
  87430. this._runTask(task);
  87431. }
  87432. return this;
  87433. };
  87434. return AssetsManager;
  87435. }());
  87436. BABYLON.AssetsManager = AssetsManager;
  87437. })(BABYLON || (BABYLON = {}));
  87438. //# sourceMappingURL=babylon.assetsManager.js.map
  87439. "use strict";
  87440. var BABYLON;
  87441. (function (BABYLON) {
  87442. var serializedGeometries = [];
  87443. var serializeGeometry = function (geometry, serializationGeometries) {
  87444. if (serializedGeometries[geometry.id]) {
  87445. return;
  87446. }
  87447. if (geometry.doNotSerialize) {
  87448. return;
  87449. }
  87450. if (geometry instanceof BABYLON.BoxGeometry) {
  87451. serializationGeometries.boxes.push(geometry.serialize());
  87452. }
  87453. else if (geometry instanceof BABYLON.SphereGeometry) {
  87454. serializationGeometries.spheres.push(geometry.serialize());
  87455. }
  87456. else if (geometry instanceof BABYLON.CylinderGeometry) {
  87457. serializationGeometries.cylinders.push(geometry.serialize());
  87458. }
  87459. else if (geometry instanceof BABYLON.TorusGeometry) {
  87460. serializationGeometries.toruses.push(geometry.serialize());
  87461. }
  87462. else if (geometry instanceof BABYLON.GroundGeometry) {
  87463. serializationGeometries.grounds.push(geometry.serialize());
  87464. }
  87465. else if (geometry instanceof BABYLON.Plane) {
  87466. serializationGeometries.planes.push(geometry.serialize());
  87467. }
  87468. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  87469. serializationGeometries.torusKnots.push(geometry.serialize());
  87470. }
  87471. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  87472. throw new Error("Unknown primitive type");
  87473. }
  87474. else {
  87475. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  87476. }
  87477. serializedGeometries[geometry.id] = true;
  87478. };
  87479. var serializeMesh = function (mesh, serializationScene) {
  87480. var serializationObject = {};
  87481. // Geometry
  87482. var geometry = mesh._geometry;
  87483. if (geometry) {
  87484. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  87485. // 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
  87486. serializeGeometry(geometry, serializationScene.geometries);
  87487. }
  87488. }
  87489. // Custom
  87490. if (mesh.serialize) {
  87491. mesh.serialize(serializationObject);
  87492. }
  87493. return serializationObject;
  87494. };
  87495. var finalizeSingleMesh = function (mesh, serializationObject) {
  87496. //only works if the mesh is already loaded
  87497. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87498. //serialize material
  87499. if (mesh.material) {
  87500. if (mesh.material instanceof BABYLON.StandardMaterial) {
  87501. serializationObject.materials = serializationObject.materials || [];
  87502. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87503. serializationObject.materials.push(mesh.material.serialize());
  87504. }
  87505. }
  87506. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  87507. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  87508. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  87509. serializationObject.multiMaterials.push(mesh.material.serialize());
  87510. }
  87511. }
  87512. }
  87513. //serialize geometry
  87514. var geometry = mesh._geometry;
  87515. if (geometry) {
  87516. if (!serializationObject.geometries) {
  87517. serializationObject.geometries = {};
  87518. serializationObject.geometries.boxes = [];
  87519. serializationObject.geometries.spheres = [];
  87520. serializationObject.geometries.cylinders = [];
  87521. serializationObject.geometries.toruses = [];
  87522. serializationObject.geometries.grounds = [];
  87523. serializationObject.geometries.planes = [];
  87524. serializationObject.geometries.torusKnots = [];
  87525. serializationObject.geometries.vertexData = [];
  87526. }
  87527. serializeGeometry(geometry, serializationObject.geometries);
  87528. }
  87529. // Skeletons
  87530. if (mesh.skeleton) {
  87531. serializationObject.skeletons = serializationObject.skeletons || [];
  87532. serializationObject.skeletons.push(mesh.skeleton.serialize());
  87533. }
  87534. //serialize the actual mesh
  87535. serializationObject.meshes = serializationObject.meshes || [];
  87536. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87537. }
  87538. };
  87539. var SceneSerializer = /** @class */ (function () {
  87540. function SceneSerializer() {
  87541. }
  87542. SceneSerializer.ClearCache = function () {
  87543. serializedGeometries = [];
  87544. };
  87545. SceneSerializer.Serialize = function (scene) {
  87546. var serializationObject = {};
  87547. SceneSerializer.ClearCache();
  87548. // Scene
  87549. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  87550. serializationObject.autoClear = scene.autoClear;
  87551. serializationObject.clearColor = scene.clearColor.asArray();
  87552. serializationObject.ambientColor = scene.ambientColor.asArray();
  87553. serializationObject.gravity = scene.gravity.asArray();
  87554. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  87555. serializationObject.workerCollisions = scene.workerCollisions;
  87556. // Fog
  87557. if (scene.fogMode && scene.fogMode !== 0) {
  87558. serializationObject.fogMode = scene.fogMode;
  87559. serializationObject.fogColor = scene.fogColor.asArray();
  87560. serializationObject.fogStart = scene.fogStart;
  87561. serializationObject.fogEnd = scene.fogEnd;
  87562. serializationObject.fogDensity = scene.fogDensity;
  87563. }
  87564. //Physics
  87565. if (scene.isPhysicsEnabled()) {
  87566. var physicEngine = scene.getPhysicsEngine();
  87567. if (physicEngine) {
  87568. serializationObject.physicsEnabled = true;
  87569. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  87570. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  87571. }
  87572. }
  87573. // Metadata
  87574. if (scene.metadata) {
  87575. serializationObject.metadata = scene.metadata;
  87576. }
  87577. // Morph targets
  87578. serializationObject.morphTargetManagers = [];
  87579. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  87580. var abstractMesh = _a[_i];
  87581. var manager = abstractMesh.morphTargetManager;
  87582. if (manager) {
  87583. serializationObject.morphTargetManagers.push(manager.serialize());
  87584. }
  87585. }
  87586. // Lights
  87587. serializationObject.lights = [];
  87588. var index;
  87589. var light;
  87590. for (index = 0; index < scene.lights.length; index++) {
  87591. light = scene.lights[index];
  87592. if (!light.doNotSerialize) {
  87593. serializationObject.lights.push(light.serialize());
  87594. }
  87595. }
  87596. // Cameras
  87597. serializationObject.cameras = [];
  87598. for (index = 0; index < scene.cameras.length; index++) {
  87599. var camera = scene.cameras[index];
  87600. if (!camera.doNotSerialize) {
  87601. serializationObject.cameras.push(camera.serialize());
  87602. }
  87603. }
  87604. if (scene.activeCamera) {
  87605. serializationObject.activeCameraID = scene.activeCamera.id;
  87606. }
  87607. // Animations
  87608. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  87609. // Materials
  87610. serializationObject.materials = [];
  87611. serializationObject.multiMaterials = [];
  87612. var material;
  87613. for (index = 0; index < scene.materials.length; index++) {
  87614. material = scene.materials[index];
  87615. if (!material.doNotSerialize) {
  87616. serializationObject.materials.push(material.serialize());
  87617. }
  87618. }
  87619. // MultiMaterials
  87620. serializationObject.multiMaterials = [];
  87621. for (index = 0; index < scene.multiMaterials.length; index++) {
  87622. var multiMaterial = scene.multiMaterials[index];
  87623. serializationObject.multiMaterials.push(multiMaterial.serialize());
  87624. }
  87625. // Environment texture
  87626. if (scene.environmentTexture) {
  87627. serializationObject.environmentTexture = scene.environmentTexture.name;
  87628. }
  87629. // Skeletons
  87630. serializationObject.skeletons = [];
  87631. for (index = 0; index < scene.skeletons.length; index++) {
  87632. var skeleton = scene.skeletons[index];
  87633. if (!skeleton.doNotSerialize) {
  87634. serializationObject.skeletons.push(skeleton.serialize());
  87635. }
  87636. }
  87637. // Transform nodes
  87638. serializationObject.transformNodes = [];
  87639. for (index = 0; index < scene.transformNodes.length; index++) {
  87640. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  87641. }
  87642. // Geometries
  87643. serializationObject.geometries = {};
  87644. serializationObject.geometries.boxes = [];
  87645. serializationObject.geometries.spheres = [];
  87646. serializationObject.geometries.cylinders = [];
  87647. serializationObject.geometries.toruses = [];
  87648. serializationObject.geometries.grounds = [];
  87649. serializationObject.geometries.planes = [];
  87650. serializationObject.geometries.torusKnots = [];
  87651. serializationObject.geometries.vertexData = [];
  87652. serializedGeometries = [];
  87653. var geometries = scene.getGeometries();
  87654. for (index = 0; index < geometries.length; index++) {
  87655. var geometry = geometries[index];
  87656. if (geometry.isReady()) {
  87657. serializeGeometry(geometry, serializationObject.geometries);
  87658. }
  87659. }
  87660. // Meshes
  87661. serializationObject.meshes = [];
  87662. for (index = 0; index < scene.meshes.length; index++) {
  87663. var abstractMesh = scene.meshes[index];
  87664. if (abstractMesh instanceof BABYLON.Mesh) {
  87665. var mesh = abstractMesh;
  87666. if (!mesh.doNotSerialize) {
  87667. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  87668. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  87669. }
  87670. }
  87671. }
  87672. }
  87673. // Particles Systems
  87674. serializationObject.particleSystems = [];
  87675. for (index = 0; index < scene.particleSystems.length; index++) {
  87676. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  87677. }
  87678. // Lens flares
  87679. serializationObject.lensFlareSystems = [];
  87680. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  87681. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  87682. }
  87683. // Shadows
  87684. serializationObject.shadowGenerators = [];
  87685. for (index = 0; index < scene.lights.length; index++) {
  87686. light = scene.lights[index];
  87687. var shadowGenerator = light.getShadowGenerator();
  87688. if (shadowGenerator) {
  87689. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  87690. }
  87691. }
  87692. // Action Manager
  87693. if (scene.actionManager) {
  87694. serializationObject.actions = scene.actionManager.serialize("scene");
  87695. }
  87696. // Audio
  87697. serializationObject.sounds = [];
  87698. for (index = 0; index < scene.soundTracks.length; index++) {
  87699. var soundtrack = scene.soundTracks[index];
  87700. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  87701. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  87702. }
  87703. }
  87704. return serializationObject;
  87705. };
  87706. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  87707. if (withParents === void 0) { withParents = false; }
  87708. if (withChildren === void 0) { withChildren = false; }
  87709. var serializationObject = {};
  87710. SceneSerializer.ClearCache();
  87711. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  87712. if (withParents || withChildren) {
  87713. //deliberate for loop! not for each, appended should be processed as well.
  87714. for (var i = 0; i < toSerialize.length; ++i) {
  87715. if (withChildren) {
  87716. toSerialize[i].getDescendants().forEach(function (node) {
  87717. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  87718. toSerialize.push(node);
  87719. }
  87720. });
  87721. }
  87722. //make sure the array doesn't contain the object already
  87723. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  87724. toSerialize.push(toSerialize[i].parent);
  87725. }
  87726. }
  87727. }
  87728. toSerialize.forEach(function (mesh) {
  87729. finalizeSingleMesh(mesh, serializationObject);
  87730. });
  87731. return serializationObject;
  87732. };
  87733. return SceneSerializer;
  87734. }());
  87735. BABYLON.SceneSerializer = SceneSerializer;
  87736. })(BABYLON || (BABYLON = {}));
  87737. //# sourceMappingURL=babylon.sceneSerializer.js.map
  87738. "use strict";
  87739. var BABYLON;
  87740. (function (BABYLON) {
  87741. var ReflectionProbe = /** @class */ (function () {
  87742. function ReflectionProbe(name, size, scene, generateMipMaps) {
  87743. if (generateMipMaps === void 0) { generateMipMaps = true; }
  87744. var _this = this;
  87745. this.name = name;
  87746. this._viewMatrix = BABYLON.Matrix.Identity();
  87747. this._target = BABYLON.Vector3.Zero();
  87748. this._add = BABYLON.Vector3.Zero();
  87749. this._invertYAxis = false;
  87750. this.position = BABYLON.Vector3.Zero();
  87751. this._scene = scene;
  87752. this._scene.reflectionProbes.push(this);
  87753. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  87754. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  87755. switch (faceIndex) {
  87756. case 0:
  87757. _this._add.copyFromFloats(1, 0, 0);
  87758. break;
  87759. case 1:
  87760. _this._add.copyFromFloats(-1, 0, 0);
  87761. break;
  87762. case 2:
  87763. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  87764. break;
  87765. case 3:
  87766. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  87767. break;
  87768. case 4:
  87769. _this._add.copyFromFloats(0, 0, 1);
  87770. break;
  87771. case 5:
  87772. _this._add.copyFromFloats(0, 0, -1);
  87773. break;
  87774. }
  87775. if (_this._attachedMesh) {
  87776. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  87777. }
  87778. _this.position.addToRef(_this._add, _this._target);
  87779. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  87780. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  87781. scene._forcedViewPosition = _this.position;
  87782. });
  87783. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  87784. scene._forcedViewPosition = null;
  87785. scene.updateTransformMatrix(true);
  87786. });
  87787. if (scene.activeCamera) {
  87788. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  87789. }
  87790. }
  87791. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  87792. get: function () {
  87793. return this._renderTargetTexture.samples;
  87794. },
  87795. set: function (value) {
  87796. this._renderTargetTexture.samples = value;
  87797. },
  87798. enumerable: true,
  87799. configurable: true
  87800. });
  87801. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  87802. get: function () {
  87803. return this._renderTargetTexture.refreshRate;
  87804. },
  87805. set: function (value) {
  87806. this._renderTargetTexture.refreshRate = value;
  87807. },
  87808. enumerable: true,
  87809. configurable: true
  87810. });
  87811. ReflectionProbe.prototype.getScene = function () {
  87812. return this._scene;
  87813. };
  87814. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  87815. get: function () {
  87816. return this._renderTargetTexture;
  87817. },
  87818. enumerable: true,
  87819. configurable: true
  87820. });
  87821. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  87822. get: function () {
  87823. return this._renderTargetTexture.renderList;
  87824. },
  87825. enumerable: true,
  87826. configurable: true
  87827. });
  87828. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  87829. this._attachedMesh = mesh;
  87830. };
  87831. /**
  87832. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  87833. *
  87834. * @param renderingGroupId The rendering group id corresponding to its index
  87835. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  87836. */
  87837. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  87838. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  87839. };
  87840. ReflectionProbe.prototype.dispose = function () {
  87841. var index = this._scene.reflectionProbes.indexOf(this);
  87842. if (index !== -1) {
  87843. // Remove from the scene if found
  87844. this._scene.reflectionProbes.splice(index, 1);
  87845. }
  87846. if (this._renderTargetTexture) {
  87847. this._renderTargetTexture.dispose();
  87848. this._renderTargetTexture = null;
  87849. }
  87850. };
  87851. return ReflectionProbe;
  87852. }());
  87853. BABYLON.ReflectionProbe = ReflectionProbe;
  87854. })(BABYLON || (BABYLON = {}));
  87855. //# sourceMappingURL=babylon.reflectionProbe.js.map
  87856. "use strict";
  87857. var BABYLON;
  87858. (function (BABYLON) {
  87859. var Layer = /** @class */ (function () {
  87860. function Layer(name, imgUrl, scene, isBackground, color) {
  87861. this.name = name;
  87862. this.scale = new BABYLON.Vector2(1, 1);
  87863. this.offset = new BABYLON.Vector2(0, 0);
  87864. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  87865. this.layerMask = 0x0FFFFFFF;
  87866. this._vertexBuffers = {};
  87867. // Events
  87868. /**
  87869. * An event triggered when the layer is disposed.
  87870. * @type {BABYLON.Observable}
  87871. */
  87872. this.onDisposeObservable = new BABYLON.Observable();
  87873. /**
  87874. * An event triggered before rendering the scene
  87875. * @type {BABYLON.Observable}
  87876. */
  87877. this.onBeforeRenderObservable = new BABYLON.Observable();
  87878. /**
  87879. * An event triggered after rendering the scene
  87880. * @type {BABYLON.Observable}
  87881. */
  87882. this.onAfterRenderObservable = new BABYLON.Observable();
  87883. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  87884. this.isBackground = isBackground === undefined ? true : isBackground;
  87885. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  87886. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  87887. this._scene.layers.push(this);
  87888. var engine = this._scene.getEngine();
  87889. // VBO
  87890. var vertices = [];
  87891. vertices.push(1, 1);
  87892. vertices.push(-1, 1);
  87893. vertices.push(-1, -1);
  87894. vertices.push(1, -1);
  87895. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  87896. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  87897. this._createIndexBuffer();
  87898. // Effects
  87899. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  87900. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  87901. }
  87902. Object.defineProperty(Layer.prototype, "onDispose", {
  87903. set: function (callback) {
  87904. if (this._onDisposeObserver) {
  87905. this.onDisposeObservable.remove(this._onDisposeObserver);
  87906. }
  87907. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  87908. },
  87909. enumerable: true,
  87910. configurable: true
  87911. });
  87912. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  87913. set: function (callback) {
  87914. if (this._onBeforeRenderObserver) {
  87915. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  87916. }
  87917. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  87918. },
  87919. enumerable: true,
  87920. configurable: true
  87921. });
  87922. Object.defineProperty(Layer.prototype, "onAfterRender", {
  87923. set: function (callback) {
  87924. if (this._onAfterRenderObserver) {
  87925. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87926. }
  87927. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  87928. },
  87929. enumerable: true,
  87930. configurable: true
  87931. });
  87932. Layer.prototype._createIndexBuffer = function () {
  87933. var engine = this._scene.getEngine();
  87934. // Indices
  87935. var indices = [];
  87936. indices.push(0);
  87937. indices.push(1);
  87938. indices.push(2);
  87939. indices.push(0);
  87940. indices.push(2);
  87941. indices.push(3);
  87942. this._indexBuffer = engine.createIndexBuffer(indices);
  87943. };
  87944. Layer.prototype._rebuild = function () {
  87945. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87946. if (vb) {
  87947. vb._rebuild();
  87948. }
  87949. this._createIndexBuffer();
  87950. };
  87951. Layer.prototype.render = function () {
  87952. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  87953. // Check
  87954. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  87955. return;
  87956. var engine = this._scene.getEngine();
  87957. this.onBeforeRenderObservable.notifyObservers(this);
  87958. // Render
  87959. engine.enableEffect(currentEffect);
  87960. engine.setState(false);
  87961. // Texture
  87962. currentEffect.setTexture("textureSampler", this.texture);
  87963. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  87964. // Color
  87965. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  87966. // Scale / offset
  87967. currentEffect.setVector2("offset", this.offset);
  87968. currentEffect.setVector2("scale", this.scale);
  87969. // VBOs
  87970. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  87971. // Draw order
  87972. if (!this.alphaTest) {
  87973. engine.setAlphaMode(this.alphaBlendingMode);
  87974. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87975. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  87976. }
  87977. else {
  87978. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87979. }
  87980. this.onAfterRenderObservable.notifyObservers(this);
  87981. };
  87982. Layer.prototype.dispose = function () {
  87983. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87984. if (vertexBuffer) {
  87985. vertexBuffer.dispose();
  87986. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87987. }
  87988. if (this._indexBuffer) {
  87989. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87990. this._indexBuffer = null;
  87991. }
  87992. if (this.texture) {
  87993. this.texture.dispose();
  87994. this.texture = null;
  87995. }
  87996. // Remove from scene
  87997. var index = this._scene.layers.indexOf(this);
  87998. this._scene.layers.splice(index, 1);
  87999. // Callback
  88000. this.onDisposeObservable.notifyObservers(this);
  88001. this.onDisposeObservable.clear();
  88002. this.onAfterRenderObservable.clear();
  88003. this.onBeforeRenderObservable.clear();
  88004. };
  88005. return Layer;
  88006. }());
  88007. BABYLON.Layer = Layer;
  88008. })(BABYLON || (BABYLON = {}));
  88009. //# sourceMappingURL=babylon.layer.js.map
  88010. "use strict";
  88011. var BABYLON;
  88012. (function (BABYLON) {
  88013. var TextureTools = /** @class */ (function () {
  88014. function TextureTools() {
  88015. }
  88016. /**
  88017. * Uses the GPU to create a copy texture rescaled at a given size
  88018. * @param texture Texture to copy from
  88019. * @param width Desired width
  88020. * @param height Desired height
  88021. * @return Generated texture
  88022. */
  88023. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  88024. if (useBilinearMode === void 0) { useBilinearMode = true; }
  88025. var scene = texture.getScene();
  88026. var engine = scene.getEngine();
  88027. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  88028. rtt.wrapU = texture.wrapU;
  88029. rtt.wrapV = texture.wrapV;
  88030. rtt.uOffset = texture.uOffset;
  88031. rtt.vOffset = texture.vOffset;
  88032. rtt.uScale = texture.uScale;
  88033. rtt.vScale = texture.vScale;
  88034. rtt.uAng = texture.uAng;
  88035. rtt.vAng = texture.vAng;
  88036. rtt.wAng = texture.wAng;
  88037. rtt.coordinatesIndex = texture.coordinatesIndex;
  88038. rtt.level = texture.level;
  88039. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  88040. rtt._texture.isReady = false;
  88041. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88042. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88043. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88044. passPostProcess.getEffect().executeWhenCompiled(function () {
  88045. passPostProcess.onApply = function (effect) {
  88046. effect.setTexture("textureSampler", texture);
  88047. };
  88048. var internalTexture = rtt.getInternalTexture();
  88049. if (internalTexture) {
  88050. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  88051. engine.unBindFramebuffer(internalTexture);
  88052. rtt.disposeFramebufferObjects();
  88053. passPostProcess.dispose();
  88054. internalTexture.isReady = true;
  88055. }
  88056. });
  88057. return rtt;
  88058. };
  88059. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  88060. if (!scene._environmentBRDFTexture) {
  88061. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88062. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88063. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88064. scene._environmentBRDFTexture = texture;
  88065. }
  88066. return scene._environmentBRDFTexture;
  88067. };
  88068. 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=";
  88069. return TextureTools;
  88070. }());
  88071. BABYLON.TextureTools = TextureTools;
  88072. })(BABYLON || (BABYLON = {}));
  88073. //# sourceMappingURL=babylon.textureTools.js.map
  88074. "use strict";
  88075. var BABYLON;
  88076. (function (BABYLON) {
  88077. var FramingBehavior = /** @class */ (function () {
  88078. function FramingBehavior() {
  88079. this._mode = FramingBehavior.FitFrustumSidesMode;
  88080. this._radiusScale = 1.0;
  88081. this._positionScale = 0.5;
  88082. this._defaultElevation = 0.3;
  88083. this._elevationReturnTime = 1500;
  88084. this._elevationReturnWaitTime = 1000;
  88085. this._zoomStopsAnimation = false;
  88086. this._framingTime = 1500;
  88087. this._isPointerDown = false;
  88088. this._lastInteractionTime = -Infinity;
  88089. // Framing control
  88090. this._animatables = new Array();
  88091. this._betaIsAnimating = false;
  88092. }
  88093. Object.defineProperty(FramingBehavior.prototype, "name", {
  88094. get: function () {
  88095. return "Framing";
  88096. },
  88097. enumerable: true,
  88098. configurable: true
  88099. });
  88100. Object.defineProperty(FramingBehavior.prototype, "mode", {
  88101. /**
  88102. * Gets current mode used by the behavior.
  88103. */
  88104. get: function () {
  88105. return this._mode;
  88106. },
  88107. /**
  88108. * Sets the current mode used by the behavior
  88109. */
  88110. set: function (mode) {
  88111. this._mode = mode;
  88112. },
  88113. enumerable: true,
  88114. configurable: true
  88115. });
  88116. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  88117. /**
  88118. * Gets the scale applied to the radius
  88119. */
  88120. get: function () {
  88121. return this._radiusScale;
  88122. },
  88123. /**
  88124. * Sets the scale applied to the radius (1 by default)
  88125. */
  88126. set: function (radius) {
  88127. this._radiusScale = radius;
  88128. },
  88129. enumerable: true,
  88130. configurable: true
  88131. });
  88132. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  88133. /**
  88134. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88135. */
  88136. get: function () {
  88137. return this._positionScale;
  88138. },
  88139. /**
  88140. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88141. */
  88142. set: function (scale) {
  88143. this._positionScale = scale;
  88144. },
  88145. enumerable: true,
  88146. configurable: true
  88147. });
  88148. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  88149. /**
  88150. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88151. * behaviour is triggered, in radians.
  88152. */
  88153. get: function () {
  88154. return this._defaultElevation;
  88155. },
  88156. /**
  88157. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88158. * behaviour is triggered, in radians.
  88159. */
  88160. set: function (elevation) {
  88161. this._defaultElevation = elevation;
  88162. },
  88163. enumerable: true,
  88164. configurable: true
  88165. });
  88166. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  88167. /**
  88168. * Gets the time (in milliseconds) taken to return to the default beta position.
  88169. * Negative value indicates camera should not return to default.
  88170. */
  88171. get: function () {
  88172. return this._elevationReturnTime;
  88173. },
  88174. /**
  88175. * Sets the time (in milliseconds) taken to return to the default beta position.
  88176. * Negative value indicates camera should not return to default.
  88177. */
  88178. set: function (speed) {
  88179. this._elevationReturnTime = speed;
  88180. },
  88181. enumerable: true,
  88182. configurable: true
  88183. });
  88184. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  88185. /**
  88186. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88187. */
  88188. get: function () {
  88189. return this._elevationReturnWaitTime;
  88190. },
  88191. /**
  88192. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88193. */
  88194. set: function (time) {
  88195. this._elevationReturnWaitTime = time;
  88196. },
  88197. enumerable: true,
  88198. configurable: true
  88199. });
  88200. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88201. /**
  88202. * Gets the flag that indicates if user zooming should stop animation.
  88203. */
  88204. get: function () {
  88205. return this._zoomStopsAnimation;
  88206. },
  88207. /**
  88208. * Sets the flag that indicates if user zooming should stop animation.
  88209. */
  88210. set: function (flag) {
  88211. this._zoomStopsAnimation = flag;
  88212. },
  88213. enumerable: true,
  88214. configurable: true
  88215. });
  88216. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  88217. /**
  88218. * Gets the transition time when framing the mesh, in milliseconds
  88219. */
  88220. get: function () {
  88221. return this._framingTime;
  88222. },
  88223. /**
  88224. * Sets the transition time when framing the mesh, in milliseconds
  88225. */
  88226. set: function (time) {
  88227. this._framingTime = time;
  88228. },
  88229. enumerable: true,
  88230. configurable: true
  88231. });
  88232. FramingBehavior.prototype.init = function () {
  88233. // Do notihng
  88234. };
  88235. FramingBehavior.prototype.attach = function (camera) {
  88236. var _this = this;
  88237. this._attachedCamera = camera;
  88238. var scene = this._attachedCamera.getScene();
  88239. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  88240. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88241. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88242. _this._isPointerDown = true;
  88243. return;
  88244. }
  88245. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88246. _this._isPointerDown = false;
  88247. }
  88248. });
  88249. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88250. if (mesh) {
  88251. _this.zoomOnMesh(mesh);
  88252. }
  88253. });
  88254. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88255. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88256. _this._applyUserInteraction();
  88257. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  88258. // back to the default position after a given timeout
  88259. _this._maintainCameraAboveGround();
  88260. });
  88261. };
  88262. FramingBehavior.prototype.detach = function () {
  88263. if (!this._attachedCamera) {
  88264. return;
  88265. }
  88266. var scene = this._attachedCamera.getScene();
  88267. if (this._onPrePointerObservableObserver) {
  88268. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88269. }
  88270. if (this._onAfterCheckInputsObserver) {
  88271. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88272. }
  88273. if (this._onMeshTargetChangedObserver) {
  88274. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88275. }
  88276. this._attachedCamera = null;
  88277. };
  88278. /**
  88279. * Targets the given mesh and updates zoom level accordingly.
  88280. * @param mesh The mesh to target.
  88281. * @param radius Optional. If a cached radius position already exists, overrides default.
  88282. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88283. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88284. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88285. */
  88286. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88287. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88288. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88289. mesh.computeWorldMatrix(true);
  88290. var boundingBox = mesh.getBoundingInfo().boundingBox;
  88291. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  88292. };
  88293. /**
  88294. * Targets the given mesh with its children and updates zoom level accordingly.
  88295. * @param mesh The mesh to target.
  88296. * @param radius Optional. If a cached radius position already exists, overrides default.
  88297. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88298. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88299. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88300. */
  88301. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88302. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88303. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88304. mesh.computeWorldMatrix(true);
  88305. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  88306. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  88307. };
  88308. /**
  88309. * Targets the given meshes with their children and updates zoom level accordingly.
  88310. * @param meshes The mesh to target.
  88311. * @param radius Optional. If a cached radius position already exists, overrides default.
  88312. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88313. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88314. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88315. */
  88316. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  88317. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88318. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88319. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  88320. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  88321. for (var i = 0; i < meshes.length; i++) {
  88322. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  88323. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  88324. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  88325. }
  88326. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  88327. };
  88328. /**
  88329. * Targets the given mesh and updates zoom level accordingly.
  88330. * @param mesh The mesh to target.
  88331. * @param radius Optional. If a cached radius position already exists, overrides default.
  88332. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88333. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88334. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88335. */
  88336. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  88337. var _this = this;
  88338. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88339. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88340. var zoomTarget;
  88341. if (!this._attachedCamera) {
  88342. return;
  88343. }
  88344. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  88345. var bottom = minimumWorld.y;
  88346. var top = maximumWorld.y;
  88347. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  88348. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  88349. if (focusOnOriginXZ) {
  88350. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  88351. }
  88352. else {
  88353. var centerWorld = minimumWorld.add(radiusWorld);
  88354. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  88355. }
  88356. if (!this._vectorTransition) {
  88357. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  88358. }
  88359. this._betaIsAnimating = true;
  88360. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  88361. if (animatable) {
  88362. this._animatables.push(animatable);
  88363. }
  88364. // sets the radius and lower radius bounds
  88365. // Small delta ensures camera is not always at lower zoom limit.
  88366. var radius = 0;
  88367. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  88368. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88369. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  88370. radius = position;
  88371. }
  88372. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88373. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  88374. if (this._attachedCamera.lowerRadiusLimit === null) {
  88375. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  88376. }
  88377. }
  88378. // Set sensibilities
  88379. var extend = maximumWorld.subtract(minimumWorld).length();
  88380. this._attachedCamera.panningSensibility = 5000 / extend;
  88381. this._attachedCamera.wheelPrecision = 100 / radius;
  88382. // transition to new radius
  88383. if (!this._radiusTransition) {
  88384. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88385. }
  88386. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  88387. _this.stopAllAnimations();
  88388. if (onAnimationEnd) {
  88389. onAnimationEnd();
  88390. }
  88391. if (_this._attachedCamera) {
  88392. _this._attachedCamera.storeState();
  88393. }
  88394. });
  88395. if (animatable) {
  88396. this._animatables.push(animatable);
  88397. }
  88398. };
  88399. /**
  88400. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  88401. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  88402. * frustum width.
  88403. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  88404. * to fully enclose the mesh in the viewing frustum.
  88405. */
  88406. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  88407. var size = maximumWorld.subtract(minimumWorld);
  88408. var boxVectorGlobalDiagonal = size.length();
  88409. var frustumSlope = this._getFrustumSlope();
  88410. // Formula for setting distance
  88411. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  88412. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  88413. // Horizon distance
  88414. var radius = radiusWithoutFraming * this._radiusScale;
  88415. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  88416. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  88417. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  88418. var camera = this._attachedCamera;
  88419. if (!camera) {
  88420. return 0;
  88421. }
  88422. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  88423. // Don't exceed the requested limit
  88424. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  88425. }
  88426. // Don't exceed the upper radius limit
  88427. if (camera.upperRadiusLimit) {
  88428. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  88429. }
  88430. return distance;
  88431. };
  88432. /**
  88433. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  88434. * is automatically returned to its default position (expected to be above ground plane).
  88435. */
  88436. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  88437. var _this = this;
  88438. if (this._elevationReturnTime < 0) {
  88439. return;
  88440. }
  88441. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  88442. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  88443. var limitBeta = Math.PI * 0.5;
  88444. // Bring the camera back up if below the ground plane
  88445. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  88446. this._betaIsAnimating = true;
  88447. //Transition to new position
  88448. this.stopAllAnimations();
  88449. if (!this._betaTransition) {
  88450. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  88451. }
  88452. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  88453. _this._clearAnimationLocks();
  88454. _this.stopAllAnimations();
  88455. });
  88456. if (animatabe) {
  88457. this._animatables.push(animatabe);
  88458. }
  88459. }
  88460. };
  88461. /**
  88462. * Returns the frustum slope based on the canvas ratio and camera FOV
  88463. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  88464. */
  88465. FramingBehavior.prototype._getFrustumSlope = function () {
  88466. // Calculate the viewport ratio
  88467. // Aspect Ratio is Height/Width.
  88468. var camera = this._attachedCamera;
  88469. if (!camera) {
  88470. return BABYLON.Vector2.Zero();
  88471. }
  88472. var engine = camera.getScene().getEngine();
  88473. var aspectRatio = engine.getAspectRatio(camera);
  88474. // Camera FOV is the vertical field of view (top-bottom) in radians.
  88475. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  88476. var frustumSlopeY = Math.tan(camera.fov / 2);
  88477. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  88478. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  88479. // along the forward vector.
  88480. var frustumSlopeX = frustumSlopeY * aspectRatio;
  88481. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  88482. };
  88483. /**
  88484. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  88485. */
  88486. FramingBehavior.prototype._clearAnimationLocks = function () {
  88487. this._betaIsAnimating = false;
  88488. };
  88489. /**
  88490. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88491. */
  88492. FramingBehavior.prototype._applyUserInteraction = function () {
  88493. if (this.isUserIsMoving) {
  88494. this._lastInteractionTime = BABYLON.Tools.Now;
  88495. this.stopAllAnimations();
  88496. this._clearAnimationLocks();
  88497. }
  88498. };
  88499. /**
  88500. * Stops and removes all animations that have been applied to the camera
  88501. */
  88502. FramingBehavior.prototype.stopAllAnimations = function () {
  88503. if (this._attachedCamera) {
  88504. this._attachedCamera.animations = [];
  88505. }
  88506. while (this._animatables.length) {
  88507. if (this._animatables[0]) {
  88508. this._animatables[0].onAnimationEnd = null;
  88509. this._animatables[0].stop();
  88510. }
  88511. this._animatables.shift();
  88512. }
  88513. };
  88514. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  88515. /**
  88516. * Gets a value indicating if the user is moving the camera
  88517. */
  88518. get: function () {
  88519. if (!this._attachedCamera) {
  88520. return false;
  88521. }
  88522. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88523. this._attachedCamera.inertialBetaOffset !== 0 ||
  88524. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88525. this._attachedCamera.inertialPanningX !== 0 ||
  88526. this._attachedCamera.inertialPanningY !== 0 ||
  88527. this._isPointerDown;
  88528. },
  88529. enumerable: true,
  88530. configurable: true
  88531. });
  88532. /**
  88533. * The easing function used by animations
  88534. */
  88535. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  88536. /**
  88537. * The easing mode used by animations
  88538. */
  88539. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  88540. // Statics
  88541. /**
  88542. * The camera can move all the way towards the mesh.
  88543. */
  88544. FramingBehavior.IgnoreBoundsSizeMode = 0;
  88545. /**
  88546. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  88547. */
  88548. FramingBehavior.FitFrustumSidesMode = 1;
  88549. return FramingBehavior;
  88550. }());
  88551. BABYLON.FramingBehavior = FramingBehavior;
  88552. })(BABYLON || (BABYLON = {}));
  88553. //# sourceMappingURL=babylon.framingBehavior.js.map
  88554. "use strict";
  88555. var BABYLON;
  88556. (function (BABYLON) {
  88557. /**
  88558. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  88559. */
  88560. var BouncingBehavior = /** @class */ (function () {
  88561. function BouncingBehavior() {
  88562. /**
  88563. * The duration of the animation, in milliseconds
  88564. */
  88565. this.transitionDuration = 450;
  88566. /**
  88567. * Length of the distance animated by the transition when lower radius is reached
  88568. */
  88569. this.lowerRadiusTransitionRange = 2;
  88570. /**
  88571. * Length of the distance animated by the transition when upper radius is reached
  88572. */
  88573. this.upperRadiusTransitionRange = -2;
  88574. this._autoTransitionRange = false;
  88575. // Animations
  88576. this._radiusIsAnimating = false;
  88577. this._radiusBounceTransition = null;
  88578. this._animatables = new Array();
  88579. }
  88580. Object.defineProperty(BouncingBehavior.prototype, "name", {
  88581. get: function () {
  88582. return "Bouncing";
  88583. },
  88584. enumerable: true,
  88585. configurable: true
  88586. });
  88587. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  88588. /**
  88589. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88590. */
  88591. get: function () {
  88592. return this._autoTransitionRange;
  88593. },
  88594. /**
  88595. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  88596. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  88597. */
  88598. set: function (value) {
  88599. var _this = this;
  88600. if (this._autoTransitionRange === value) {
  88601. return;
  88602. }
  88603. this._autoTransitionRange = value;
  88604. var camera = this._attachedCamera;
  88605. if (!camera) {
  88606. return;
  88607. }
  88608. if (value) {
  88609. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88610. if (!mesh) {
  88611. return;
  88612. }
  88613. mesh.computeWorldMatrix(true);
  88614. var diagonal = mesh.getBoundingInfo().diagonalLength;
  88615. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  88616. _this.upperRadiusTransitionRange = diagonal * 0.05;
  88617. });
  88618. }
  88619. else if (this._onMeshTargetChangedObserver) {
  88620. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88621. }
  88622. },
  88623. enumerable: true,
  88624. configurable: true
  88625. });
  88626. BouncingBehavior.prototype.init = function () {
  88627. // Do notihng
  88628. };
  88629. BouncingBehavior.prototype.attach = function (camera) {
  88630. var _this = this;
  88631. this._attachedCamera = camera;
  88632. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88633. if (!_this._attachedCamera) {
  88634. return;
  88635. }
  88636. // Add the bounce animation to the lower radius limit
  88637. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  88638. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  88639. }
  88640. // Add the bounce animation to the upper radius limit
  88641. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  88642. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  88643. }
  88644. });
  88645. };
  88646. BouncingBehavior.prototype.detach = function () {
  88647. if (!this._attachedCamera) {
  88648. return;
  88649. }
  88650. if (this._onAfterCheckInputsObserver) {
  88651. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88652. }
  88653. if (this._onMeshTargetChangedObserver) {
  88654. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88655. }
  88656. this._attachedCamera = null;
  88657. };
  88658. /**
  88659. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  88660. * @param radiusLimit The limit to check against.
  88661. * @return Bool to indicate if at limit.
  88662. */
  88663. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  88664. if (!this._attachedCamera) {
  88665. return false;
  88666. }
  88667. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  88668. return true;
  88669. }
  88670. return false;
  88671. };
  88672. /**
  88673. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  88674. * @param radiusDelta The delta by which to animate to. Can be negative.
  88675. */
  88676. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  88677. var _this = this;
  88678. if (!this._attachedCamera) {
  88679. return;
  88680. }
  88681. if (!this._radiusBounceTransition) {
  88682. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  88683. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  88684. }
  88685. // Prevent zoom until bounce has completed
  88686. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  88687. this._attachedCamera.wheelPrecision = Infinity;
  88688. this._attachedCamera.inertialRadiusOffset = 0;
  88689. // Animate to the radius limit
  88690. this.stopAllAnimations();
  88691. this._radiusIsAnimating = true;
  88692. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  88693. if (animatable) {
  88694. this._animatables.push(animatable);
  88695. }
  88696. };
  88697. /**
  88698. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  88699. */
  88700. BouncingBehavior.prototype._clearAnimationLocks = function () {
  88701. this._radiusIsAnimating = false;
  88702. if (this._attachedCamera) {
  88703. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  88704. }
  88705. };
  88706. /**
  88707. * Stops and removes all animations that have been applied to the camera
  88708. */
  88709. BouncingBehavior.prototype.stopAllAnimations = function () {
  88710. if (this._attachedCamera) {
  88711. this._attachedCamera.animations = [];
  88712. }
  88713. while (this._animatables.length) {
  88714. this._animatables[0].onAnimationEnd = null;
  88715. this._animatables[0].stop();
  88716. this._animatables.shift();
  88717. }
  88718. };
  88719. /**
  88720. * The easing function used by animations
  88721. */
  88722. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  88723. /**
  88724. * The easing mode used by animations
  88725. */
  88726. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  88727. return BouncingBehavior;
  88728. }());
  88729. BABYLON.BouncingBehavior = BouncingBehavior;
  88730. })(BABYLON || (BABYLON = {}));
  88731. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  88732. "use strict";
  88733. var BABYLON;
  88734. (function (BABYLON) {
  88735. var AutoRotationBehavior = /** @class */ (function () {
  88736. function AutoRotationBehavior() {
  88737. this._zoomStopsAnimation = false;
  88738. this._idleRotationSpeed = 0.05;
  88739. this._idleRotationWaitTime = 2000;
  88740. this._idleRotationSpinupTime = 2000;
  88741. this._isPointerDown = false;
  88742. this._lastFrameTime = null;
  88743. this._lastInteractionTime = -Infinity;
  88744. this._cameraRotationSpeed = 0;
  88745. this._lastFrameRadius = 0;
  88746. }
  88747. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  88748. get: function () {
  88749. return "AutoRotation";
  88750. },
  88751. enumerable: true,
  88752. configurable: true
  88753. });
  88754. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  88755. /**
  88756. * Gets the flag that indicates if user zooming should stop animation.
  88757. */
  88758. get: function () {
  88759. return this._zoomStopsAnimation;
  88760. },
  88761. /**
  88762. * Sets the flag that indicates if user zooming should stop animation.
  88763. */
  88764. set: function (flag) {
  88765. this._zoomStopsAnimation = flag;
  88766. },
  88767. enumerable: true,
  88768. configurable: true
  88769. });
  88770. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  88771. /**
  88772. * Gets the default speed at which the camera rotates around the model.
  88773. */
  88774. get: function () {
  88775. return this._idleRotationSpeed;
  88776. },
  88777. /**
  88778. * Sets the default speed at which the camera rotates around the model.
  88779. */
  88780. set: function (speed) {
  88781. this._idleRotationSpeed = speed;
  88782. },
  88783. enumerable: true,
  88784. configurable: true
  88785. });
  88786. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  88787. /**
  88788. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  88789. */
  88790. get: function () {
  88791. return this._idleRotationWaitTime;
  88792. },
  88793. /**
  88794. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  88795. */
  88796. set: function (time) {
  88797. this._idleRotationWaitTime = time;
  88798. },
  88799. enumerable: true,
  88800. configurable: true
  88801. });
  88802. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  88803. /**
  88804. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88805. */
  88806. get: function () {
  88807. return this._idleRotationSpinupTime;
  88808. },
  88809. /**
  88810. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  88811. */
  88812. set: function (time) {
  88813. this._idleRotationSpinupTime = time;
  88814. },
  88815. enumerable: true,
  88816. configurable: true
  88817. });
  88818. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  88819. /**
  88820. * Gets a value indicating if the camera is currently rotating because of this behavior
  88821. */
  88822. get: function () {
  88823. return Math.abs(this._cameraRotationSpeed) > 0;
  88824. },
  88825. enumerable: true,
  88826. configurable: true
  88827. });
  88828. AutoRotationBehavior.prototype.init = function () {
  88829. // Do notihng
  88830. };
  88831. AutoRotationBehavior.prototype.attach = function (camera) {
  88832. var _this = this;
  88833. this._attachedCamera = camera;
  88834. var scene = this._attachedCamera.getScene();
  88835. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88836. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88837. _this._isPointerDown = true;
  88838. return;
  88839. }
  88840. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88841. _this._isPointerDown = false;
  88842. }
  88843. });
  88844. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88845. var now = BABYLON.Tools.Now;
  88846. var dt = 0;
  88847. if (_this._lastFrameTime != null) {
  88848. dt = now - _this._lastFrameTime;
  88849. }
  88850. _this._lastFrameTime = now;
  88851. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88852. _this._applyUserInteraction();
  88853. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  88854. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  88855. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  88856. // Step camera rotation by rotation speed
  88857. if (_this._attachedCamera) {
  88858. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  88859. }
  88860. });
  88861. };
  88862. AutoRotationBehavior.prototype.detach = function () {
  88863. if (!this._attachedCamera) {
  88864. return;
  88865. }
  88866. var scene = this._attachedCamera.getScene();
  88867. if (this._onPrePointerObservableObserver) {
  88868. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88869. }
  88870. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88871. this._attachedCamera = null;
  88872. };
  88873. /**
  88874. * Returns true if user is scrolling.
  88875. * @return true if user is scrolling.
  88876. */
  88877. AutoRotationBehavior.prototype._userIsZooming = function () {
  88878. if (!this._attachedCamera) {
  88879. return false;
  88880. }
  88881. return this._attachedCamera.inertialRadiusOffset !== 0;
  88882. };
  88883. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  88884. if (!this._attachedCamera) {
  88885. return false;
  88886. }
  88887. var zoomHasHitLimit = false;
  88888. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  88889. zoomHasHitLimit = true;
  88890. }
  88891. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  88892. this._lastFrameRadius = this._attachedCamera.radius;
  88893. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  88894. };
  88895. /**
  88896. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  88897. */
  88898. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  88899. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  88900. this._lastInteractionTime = BABYLON.Tools.Now;
  88901. }
  88902. };
  88903. // Tools
  88904. AutoRotationBehavior.prototype._userIsMoving = function () {
  88905. if (!this._attachedCamera) {
  88906. return false;
  88907. }
  88908. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  88909. this._attachedCamera.inertialBetaOffset !== 0 ||
  88910. this._attachedCamera.inertialRadiusOffset !== 0 ||
  88911. this._attachedCamera.inertialPanningX !== 0 ||
  88912. this._attachedCamera.inertialPanningY !== 0 ||
  88913. this._isPointerDown;
  88914. };
  88915. return AutoRotationBehavior;
  88916. }());
  88917. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  88918. })(BABYLON || (BABYLON = {}));
  88919. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  88920. "use strict";
  88921. var BABYLON;
  88922. (function (BABYLON) {
  88923. /**
  88924. * This class can be used to get instrumentation data from a Babylon engine
  88925. */
  88926. var EngineInstrumentation = /** @class */ (function () {
  88927. function EngineInstrumentation(engine) {
  88928. this.engine = engine;
  88929. this._captureGPUFrameTime = false;
  88930. this._gpuFrameTime = new BABYLON.PerfCounter();
  88931. this._captureShaderCompilationTime = false;
  88932. this._shaderCompilationTime = new BABYLON.PerfCounter();
  88933. // Observers
  88934. this._onBeginFrameObserver = null;
  88935. this._onEndFrameObserver = null;
  88936. this._onBeforeShaderCompilationObserver = null;
  88937. this._onAfterShaderCompilationObserver = null;
  88938. }
  88939. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  88940. // Properties
  88941. /**
  88942. * Gets the perf counter used for GPU frame time
  88943. */
  88944. get: function () {
  88945. return this._gpuFrameTime;
  88946. },
  88947. enumerable: true,
  88948. configurable: true
  88949. });
  88950. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  88951. /**
  88952. * Gets the GPU frame time capture status
  88953. */
  88954. get: function () {
  88955. return this._captureGPUFrameTime;
  88956. },
  88957. /**
  88958. * Enable or disable the GPU frame time capture
  88959. */
  88960. set: function (value) {
  88961. var _this = this;
  88962. if (value === this._captureGPUFrameTime) {
  88963. return;
  88964. }
  88965. this._captureGPUFrameTime = value;
  88966. if (value) {
  88967. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  88968. if (!_this._gpuFrameTimeToken) {
  88969. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  88970. }
  88971. });
  88972. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  88973. if (!_this._gpuFrameTimeToken) {
  88974. return;
  88975. }
  88976. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  88977. if (time > -1) {
  88978. _this._gpuFrameTimeToken = null;
  88979. _this._gpuFrameTime.fetchNewFrame();
  88980. _this._gpuFrameTime.addCount(time, true);
  88981. }
  88982. });
  88983. }
  88984. else {
  88985. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  88986. this._onBeginFrameObserver = null;
  88987. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  88988. this._onEndFrameObserver = null;
  88989. }
  88990. },
  88991. enumerable: true,
  88992. configurable: true
  88993. });
  88994. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  88995. /**
  88996. * Gets the perf counter used for shader compilation time
  88997. */
  88998. get: function () {
  88999. return this._shaderCompilationTime;
  89000. },
  89001. enumerable: true,
  89002. configurable: true
  89003. });
  89004. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  89005. /**
  89006. * Gets the shader compilation time capture status
  89007. */
  89008. get: function () {
  89009. return this._captureShaderCompilationTime;
  89010. },
  89011. /**
  89012. * Enable or disable the shader compilation time capture
  89013. */
  89014. set: function (value) {
  89015. var _this = this;
  89016. if (value === this._captureShaderCompilationTime) {
  89017. return;
  89018. }
  89019. this._captureShaderCompilationTime = value;
  89020. if (value) {
  89021. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  89022. _this._shaderCompilationTime.fetchNewFrame();
  89023. _this._shaderCompilationTime.beginMonitoring();
  89024. });
  89025. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  89026. _this._shaderCompilationTime.endMonitoring();
  89027. });
  89028. }
  89029. else {
  89030. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89031. this._onBeforeShaderCompilationObserver = null;
  89032. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89033. this._onAfterShaderCompilationObserver = null;
  89034. }
  89035. },
  89036. enumerable: true,
  89037. configurable: true
  89038. });
  89039. EngineInstrumentation.prototype.dispose = function () {
  89040. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  89041. this._onBeginFrameObserver = null;
  89042. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  89043. this._onEndFrameObserver = null;
  89044. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  89045. this._onBeforeShaderCompilationObserver = null;
  89046. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  89047. this._onAfterShaderCompilationObserver = null;
  89048. this.engine = null;
  89049. };
  89050. return EngineInstrumentation;
  89051. }());
  89052. BABYLON.EngineInstrumentation = EngineInstrumentation;
  89053. })(BABYLON || (BABYLON = {}));
  89054. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  89055. "use strict";
  89056. var BABYLON;
  89057. (function (BABYLON) {
  89058. /**
  89059. * This class can be used to get instrumentation data from a Babylon engine
  89060. */
  89061. var SceneInstrumentation = /** @class */ (function () {
  89062. function SceneInstrumentation(scene) {
  89063. var _this = this;
  89064. this.scene = scene;
  89065. this._captureActiveMeshesEvaluationTime = false;
  89066. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  89067. this._captureRenderTargetsRenderTime = false;
  89068. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  89069. this._captureFrameTime = false;
  89070. this._frameTime = new BABYLON.PerfCounter();
  89071. this._captureRenderTime = false;
  89072. this._renderTime = new BABYLON.PerfCounter();
  89073. this._captureInterFrameTime = false;
  89074. this._interFrameTime = new BABYLON.PerfCounter();
  89075. this._captureParticlesRenderTime = false;
  89076. this._particlesRenderTime = new BABYLON.PerfCounter();
  89077. this._captureSpritesRenderTime = false;
  89078. this._spritesRenderTime = new BABYLON.PerfCounter();
  89079. this._capturePhysicsTime = false;
  89080. this._physicsTime = new BABYLON.PerfCounter();
  89081. this._captureAnimationsTime = false;
  89082. this._animationsTime = new BABYLON.PerfCounter();
  89083. // Observers
  89084. this._onBeforeActiveMeshesEvaluationObserver = null;
  89085. this._onAfterActiveMeshesEvaluationObserver = null;
  89086. this._onBeforeRenderTargetsRenderObserver = null;
  89087. this._onAfterRenderTargetsRenderObserver = null;
  89088. this._onAfterRenderObserver = null;
  89089. this._onBeforeDrawPhaseObserver = null;
  89090. this._onAfterDrawPhaseObserver = null;
  89091. this._onBeforeAnimationsObserver = null;
  89092. this._onBeforeParticlesRenderingObserver = null;
  89093. this._onAfterParticlesRenderingObserver = null;
  89094. this._onBeforeSpritesRenderingObserver = null;
  89095. this._onAfterSpritesRenderingObserver = null;
  89096. this._onBeforePhysicsObserver = null;
  89097. this._onAfterPhysicsObserver = null;
  89098. this._onAfterAnimationsObserver = null;
  89099. // Before render
  89100. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  89101. if (_this._captureActiveMeshesEvaluationTime) {
  89102. _this._activeMeshesEvaluationTime.fetchNewFrame();
  89103. }
  89104. if (_this._captureRenderTargetsRenderTime) {
  89105. _this._renderTargetsRenderTime.fetchNewFrame();
  89106. }
  89107. if (_this._captureFrameTime) {
  89108. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  89109. _this._frameTime.beginMonitoring();
  89110. }
  89111. if (_this._captureInterFrameTime) {
  89112. _this._interFrameTime.endMonitoring();
  89113. }
  89114. if (_this._captureParticlesRenderTime) {
  89115. _this._particlesRenderTime.fetchNewFrame();
  89116. }
  89117. if (_this._captureSpritesRenderTime) {
  89118. _this._spritesRenderTime.fetchNewFrame();
  89119. }
  89120. if (_this._captureAnimationsTime) {
  89121. _this._animationsTime.beginMonitoring();
  89122. }
  89123. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  89124. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  89125. });
  89126. // After render
  89127. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  89128. if (_this._captureFrameTime) {
  89129. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  89130. _this._frameTime.endMonitoring();
  89131. }
  89132. if (_this._captureRenderTime) {
  89133. _this._renderTime.endMonitoring(false);
  89134. }
  89135. if (_this._captureInterFrameTime) {
  89136. _this._interFrameTime.beginMonitoring();
  89137. }
  89138. });
  89139. }
  89140. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  89141. // Properties
  89142. /**
  89143. * Gets the perf counter used for active meshes evaluation time
  89144. */
  89145. get: function () {
  89146. return this._activeMeshesEvaluationTime;
  89147. },
  89148. enumerable: true,
  89149. configurable: true
  89150. });
  89151. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  89152. /**
  89153. * Gets the active meshes evaluation time capture status
  89154. */
  89155. get: function () {
  89156. return this._captureActiveMeshesEvaluationTime;
  89157. },
  89158. /**
  89159. * Enable or disable the active meshes evaluation time capture
  89160. */
  89161. set: function (value) {
  89162. var _this = this;
  89163. if (value === this._captureActiveMeshesEvaluationTime) {
  89164. return;
  89165. }
  89166. this._captureActiveMeshesEvaluationTime = value;
  89167. if (value) {
  89168. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  89169. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  89170. _this._activeMeshesEvaluationTime.beginMonitoring();
  89171. });
  89172. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  89173. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  89174. _this._activeMeshesEvaluationTime.endMonitoring();
  89175. });
  89176. }
  89177. else {
  89178. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89179. this._onBeforeActiveMeshesEvaluationObserver = null;
  89180. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89181. this._onAfterActiveMeshesEvaluationObserver = null;
  89182. }
  89183. },
  89184. enumerable: true,
  89185. configurable: true
  89186. });
  89187. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  89188. /**
  89189. * Gets the perf counter used for render targets render time
  89190. */
  89191. get: function () {
  89192. return this._renderTargetsRenderTime;
  89193. },
  89194. enumerable: true,
  89195. configurable: true
  89196. });
  89197. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  89198. /**
  89199. * Gets the render targets render time capture status
  89200. */
  89201. get: function () {
  89202. return this._captureRenderTargetsRenderTime;
  89203. },
  89204. /**
  89205. * Enable or disable the render targets render time capture
  89206. */
  89207. set: function (value) {
  89208. var _this = this;
  89209. if (value === this._captureRenderTargetsRenderTime) {
  89210. return;
  89211. }
  89212. this._captureRenderTargetsRenderTime = value;
  89213. if (value) {
  89214. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  89215. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  89216. _this._renderTargetsRenderTime.beginMonitoring();
  89217. });
  89218. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  89219. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  89220. _this._renderTargetsRenderTime.endMonitoring(false);
  89221. });
  89222. }
  89223. else {
  89224. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89225. this._onBeforeRenderTargetsRenderObserver = null;
  89226. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89227. this._onAfterRenderTargetsRenderObserver = null;
  89228. }
  89229. },
  89230. enumerable: true,
  89231. configurable: true
  89232. });
  89233. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  89234. /**
  89235. * Gets the perf counter used for particles render time
  89236. */
  89237. get: function () {
  89238. return this._particlesRenderTime;
  89239. },
  89240. enumerable: true,
  89241. configurable: true
  89242. });
  89243. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  89244. /**
  89245. * Gets the particles render time capture status
  89246. */
  89247. get: function () {
  89248. return this._captureParticlesRenderTime;
  89249. },
  89250. /**
  89251. * Enable or disable the particles render time capture
  89252. */
  89253. set: function (value) {
  89254. var _this = this;
  89255. if (value === this._captureParticlesRenderTime) {
  89256. return;
  89257. }
  89258. this._captureParticlesRenderTime = value;
  89259. if (value) {
  89260. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  89261. BABYLON.Tools.StartPerformanceCounter("Particles");
  89262. _this._particlesRenderTime.beginMonitoring();
  89263. });
  89264. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  89265. BABYLON.Tools.EndPerformanceCounter("Particles");
  89266. _this._particlesRenderTime.endMonitoring(false);
  89267. });
  89268. }
  89269. else {
  89270. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89271. this._onBeforeParticlesRenderingObserver = null;
  89272. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89273. this._onAfterParticlesRenderingObserver = null;
  89274. }
  89275. },
  89276. enumerable: true,
  89277. configurable: true
  89278. });
  89279. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  89280. /**
  89281. * Gets the perf counter used for sprites render time
  89282. */
  89283. get: function () {
  89284. return this._spritesRenderTime;
  89285. },
  89286. enumerable: true,
  89287. configurable: true
  89288. });
  89289. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  89290. /**
  89291. * Gets the sprites render time capture status
  89292. */
  89293. get: function () {
  89294. return this._captureSpritesRenderTime;
  89295. },
  89296. /**
  89297. * Enable or disable the sprites render time capture
  89298. */
  89299. set: function (value) {
  89300. var _this = this;
  89301. if (value === this._captureSpritesRenderTime) {
  89302. return;
  89303. }
  89304. this._captureSpritesRenderTime = value;
  89305. if (value) {
  89306. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  89307. BABYLON.Tools.StartPerformanceCounter("Sprites");
  89308. _this._spritesRenderTime.beginMonitoring();
  89309. });
  89310. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  89311. BABYLON.Tools.EndPerformanceCounter("Sprites");
  89312. _this._spritesRenderTime.endMonitoring(false);
  89313. });
  89314. }
  89315. else {
  89316. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89317. this._onBeforeSpritesRenderingObserver = null;
  89318. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89319. this._onAfterSpritesRenderingObserver = null;
  89320. }
  89321. },
  89322. enumerable: true,
  89323. configurable: true
  89324. });
  89325. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  89326. /**
  89327. * Gets the perf counter used for physics time
  89328. */
  89329. get: function () {
  89330. return this._physicsTime;
  89331. },
  89332. enumerable: true,
  89333. configurable: true
  89334. });
  89335. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  89336. /**
  89337. * Gets the physics time capture status
  89338. */
  89339. get: function () {
  89340. return this._capturePhysicsTime;
  89341. },
  89342. /**
  89343. * Enable or disable the physics time capture
  89344. */
  89345. set: function (value) {
  89346. var _this = this;
  89347. if (value === this._capturePhysicsTime) {
  89348. return;
  89349. }
  89350. this._capturePhysicsTime = value;
  89351. if (value) {
  89352. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  89353. BABYLON.Tools.StartPerformanceCounter("Physics");
  89354. _this._physicsTime.beginMonitoring();
  89355. });
  89356. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  89357. BABYLON.Tools.EndPerformanceCounter("Physics");
  89358. _this._physicsTime.endMonitoring();
  89359. });
  89360. }
  89361. else {
  89362. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89363. this._onBeforePhysicsObserver = null;
  89364. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89365. this._onAfterPhysicsObserver = null;
  89366. }
  89367. },
  89368. enumerable: true,
  89369. configurable: true
  89370. });
  89371. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  89372. /**
  89373. * Gets the perf counter used for animations time
  89374. */
  89375. get: function () {
  89376. return this._animationsTime;
  89377. },
  89378. enumerable: true,
  89379. configurable: true
  89380. });
  89381. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  89382. /**
  89383. * Gets the animations time capture status
  89384. */
  89385. get: function () {
  89386. return this._captureAnimationsTime;
  89387. },
  89388. /**
  89389. * Enable or disable the animations time capture
  89390. */
  89391. set: function (value) {
  89392. var _this = this;
  89393. if (value === this._captureAnimationsTime) {
  89394. return;
  89395. }
  89396. this._captureAnimationsTime = value;
  89397. if (value) {
  89398. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  89399. _this._animationsTime.endMonitoring();
  89400. });
  89401. }
  89402. else {
  89403. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89404. this._onAfterAnimationsObserver = null;
  89405. }
  89406. },
  89407. enumerable: true,
  89408. configurable: true
  89409. });
  89410. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  89411. /**
  89412. * Gets the perf counter used for frame time capture
  89413. */
  89414. get: function () {
  89415. return this._frameTime;
  89416. },
  89417. enumerable: true,
  89418. configurable: true
  89419. });
  89420. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  89421. /**
  89422. * Gets the frame time capture status
  89423. */
  89424. get: function () {
  89425. return this._captureFrameTime;
  89426. },
  89427. /**
  89428. * Enable or disable the frame time capture
  89429. */
  89430. set: function (value) {
  89431. this._captureFrameTime = value;
  89432. },
  89433. enumerable: true,
  89434. configurable: true
  89435. });
  89436. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  89437. /**
  89438. * Gets the perf counter used for inter-frames time capture
  89439. */
  89440. get: function () {
  89441. return this._interFrameTime;
  89442. },
  89443. enumerable: true,
  89444. configurable: true
  89445. });
  89446. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  89447. /**
  89448. * Gets the inter-frames time capture status
  89449. */
  89450. get: function () {
  89451. return this._captureInterFrameTime;
  89452. },
  89453. /**
  89454. * Enable or disable the inter-frames time capture
  89455. */
  89456. set: function (value) {
  89457. this._captureInterFrameTime = value;
  89458. },
  89459. enumerable: true,
  89460. configurable: true
  89461. });
  89462. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  89463. /**
  89464. * Gets the perf counter used for render time capture
  89465. */
  89466. get: function () {
  89467. return this._renderTime;
  89468. },
  89469. enumerable: true,
  89470. configurable: true
  89471. });
  89472. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  89473. /**
  89474. * Gets the render time capture status
  89475. */
  89476. get: function () {
  89477. return this._captureRenderTime;
  89478. },
  89479. /**
  89480. * Enable or disable the render time capture
  89481. */
  89482. set: function (value) {
  89483. var _this = this;
  89484. if (value === this._captureRenderTime) {
  89485. return;
  89486. }
  89487. this._captureRenderTime = value;
  89488. if (value) {
  89489. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  89490. _this._renderTime.beginMonitoring();
  89491. BABYLON.Tools.StartPerformanceCounter("Main render");
  89492. });
  89493. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  89494. _this._renderTime.endMonitoring(false);
  89495. BABYLON.Tools.EndPerformanceCounter("Main render");
  89496. });
  89497. }
  89498. else {
  89499. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89500. this._onBeforeDrawPhaseObserver = null;
  89501. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89502. this._onAfterDrawPhaseObserver = null;
  89503. }
  89504. },
  89505. enumerable: true,
  89506. configurable: true
  89507. });
  89508. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  89509. /**
  89510. * Gets the perf counter used for draw calls
  89511. */
  89512. get: function () {
  89513. return this.scene.getEngine()._drawCalls;
  89514. },
  89515. enumerable: true,
  89516. configurable: true
  89517. });
  89518. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  89519. /**
  89520. * Gets the perf counter used for texture collisions
  89521. */
  89522. get: function () {
  89523. return this.scene.getEngine()._textureCollisions;
  89524. },
  89525. enumerable: true,
  89526. configurable: true
  89527. });
  89528. SceneInstrumentation.prototype.dispose = function () {
  89529. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89530. this._onAfterRenderObserver = null;
  89531. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  89532. this._onBeforeActiveMeshesEvaluationObserver = null;
  89533. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  89534. this._onAfterActiveMeshesEvaluationObserver = null;
  89535. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  89536. this._onBeforeRenderTargetsRenderObserver = null;
  89537. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  89538. this._onAfterRenderTargetsRenderObserver = null;
  89539. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  89540. this._onBeforeAnimationsObserver = null;
  89541. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  89542. this._onBeforeParticlesRenderingObserver = null;
  89543. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  89544. this._onAfterParticlesRenderingObserver = null;
  89545. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  89546. this._onBeforeSpritesRenderingObserver = null;
  89547. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  89548. this._onAfterSpritesRenderingObserver = null;
  89549. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  89550. this._onBeforeDrawPhaseObserver = null;
  89551. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  89552. this._onAfterDrawPhaseObserver = null;
  89553. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  89554. this._onBeforePhysicsObserver = null;
  89555. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  89556. this._onAfterPhysicsObserver = null;
  89557. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  89558. this._onAfterAnimationsObserver = null;
  89559. this.scene = null;
  89560. };
  89561. return SceneInstrumentation;
  89562. }());
  89563. BABYLON.SceneInstrumentation = SceneInstrumentation;
  89564. })(BABYLON || (BABYLON = {}));
  89565. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  89566. "use strict";
  89567. var BABYLON;
  89568. (function (BABYLON) {
  89569. var _TimeToken = /** @class */ (function () {
  89570. function _TimeToken() {
  89571. this._timeElapsedQueryEnded = false;
  89572. }
  89573. return _TimeToken;
  89574. }());
  89575. BABYLON._TimeToken = _TimeToken;
  89576. })(BABYLON || (BABYLON = {}));
  89577. //# sourceMappingURL=babylon.timeToken.js.map
  89578. "use strict";
  89579. var BABYLON;
  89580. (function (BABYLON) {
  89581. /**
  89582. * Background material defines definition.
  89583. * @ignore Mainly internal Use
  89584. */
  89585. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  89586. __extends(BackgroundMaterialDefines, _super);
  89587. /**
  89588. * Constructor of the defines.
  89589. */
  89590. function BackgroundMaterialDefines() {
  89591. var _this = _super.call(this) || this;
  89592. /**
  89593. * True if the diffuse texture is in use.
  89594. */
  89595. _this.DIFFUSE = false;
  89596. /**
  89597. * The direct UV channel to use.
  89598. */
  89599. _this.DIFFUSEDIRECTUV = 0;
  89600. /**
  89601. * True if the diffuse texture is in gamma space.
  89602. */
  89603. _this.GAMMADIFFUSE = false;
  89604. /**
  89605. * True if the diffuse texture has opacity in the alpha channel.
  89606. */
  89607. _this.DIFFUSEHASALPHA = false;
  89608. /**
  89609. * True if you want the material to fade to transparent at grazing angle.
  89610. */
  89611. _this.OPACITYFRESNEL = false;
  89612. /**
  89613. * True if an extra blur needs to be added in the reflection.
  89614. */
  89615. _this.REFLECTIONBLUR = false;
  89616. /**
  89617. * True if you want the material to fade to reflection at grazing angle.
  89618. */
  89619. _this.REFLECTIONFRESNEL = false;
  89620. /**
  89621. * True if you want the material to falloff as far as you move away from the scene center.
  89622. */
  89623. _this.REFLECTIONFALLOFF = false;
  89624. /**
  89625. * False if the current Webgl implementation does not support the texture lod extension.
  89626. */
  89627. _this.TEXTURELODSUPPORT = false;
  89628. /**
  89629. * True to ensure the data are premultiplied.
  89630. */
  89631. _this.PREMULTIPLYALPHA = false;
  89632. /**
  89633. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  89634. */
  89635. _this.USERGBCOLOR = false;
  89636. /**
  89637. * True to add noise in order to reduce the banding effect.
  89638. */
  89639. _this.NOISE = false;
  89640. /**
  89641. * is the reflection texture in BGR color scheme?
  89642. * Mainly used to solve a bug in ios10 video tag
  89643. */
  89644. _this.REFLECTIONBGR = false;
  89645. _this.IMAGEPROCESSING = false;
  89646. _this.VIGNETTE = false;
  89647. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  89648. _this.VIGNETTEBLENDMODEOPAQUE = false;
  89649. _this.TONEMAPPING = false;
  89650. _this.CONTRAST = false;
  89651. _this.COLORCURVES = false;
  89652. _this.COLORGRADING = false;
  89653. _this.COLORGRADING3D = false;
  89654. _this.SAMPLER3DGREENDEPTH = false;
  89655. _this.SAMPLER3DBGRMAP = false;
  89656. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  89657. _this.EXPOSURE = false;
  89658. _this.GRAIN = false;
  89659. // Reflection.
  89660. _this.REFLECTION = false;
  89661. _this.REFLECTIONMAP_3D = false;
  89662. _this.REFLECTIONMAP_SPHERICAL = false;
  89663. _this.REFLECTIONMAP_PLANAR = false;
  89664. _this.REFLECTIONMAP_CUBIC = false;
  89665. _this.REFLECTIONMAP_PROJECTION = false;
  89666. _this.REFLECTIONMAP_SKYBOX = false;
  89667. _this.REFLECTIONMAP_EXPLICIT = false;
  89668. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  89669. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  89670. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  89671. _this.INVERTCUBICMAP = false;
  89672. _this.REFLECTIONMAP_OPPOSITEZ = false;
  89673. _this.LODINREFLECTIONALPHA = false;
  89674. _this.GAMMAREFLECTION = false;
  89675. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  89676. // Default BJS.
  89677. _this.MAINUV1 = false;
  89678. _this.MAINUV2 = false;
  89679. _this.UV1 = false;
  89680. _this.UV2 = false;
  89681. _this.CLIPPLANE = false;
  89682. _this.POINTSIZE = false;
  89683. _this.FOG = false;
  89684. _this.NORMAL = false;
  89685. _this.NUM_BONE_INFLUENCERS = 0;
  89686. _this.BonesPerMesh = 0;
  89687. _this.INSTANCES = false;
  89688. _this.SHADOWFLOAT = false;
  89689. _this.rebuild();
  89690. return _this;
  89691. }
  89692. return BackgroundMaterialDefines;
  89693. }(BABYLON.MaterialDefines));
  89694. /**
  89695. * Background material used to create an efficient environement around your scene.
  89696. */
  89697. var BackgroundMaterial = /** @class */ (function (_super) {
  89698. __extends(BackgroundMaterial, _super);
  89699. /**
  89700. * Instantiates a Background Material in the given scene
  89701. * @param name The friendly name of the material
  89702. * @param scene The scene to add the material to
  89703. */
  89704. function BackgroundMaterial(name, scene) {
  89705. var _this = _super.call(this, name, scene) || this;
  89706. /**
  89707. * Key light Color (multiply against the R channel of the environement texture)
  89708. */
  89709. _this.primaryColor = BABYLON.Color3.White();
  89710. /**
  89711. * Key light Level (allowing HDR output of the background)
  89712. */
  89713. _this.primaryLevel = 1;
  89714. /**
  89715. * Secondary light Color (multiply against the G channel of the environement texture)
  89716. */
  89717. _this.secondaryColor = BABYLON.Color3.Gray();
  89718. /**
  89719. * Secondary light Level (allowing HDR output of the background)
  89720. */
  89721. _this.secondaryLevel = 1;
  89722. /**
  89723. * Tertiary light Color (multiply against the B channel of the environement texture)
  89724. */
  89725. _this.tertiaryColor = BABYLON.Color3.Black();
  89726. /**
  89727. * Tertiary light Level (allowing HDR output of the background)
  89728. */
  89729. _this.tertiaryLevel = 1;
  89730. /**
  89731. * Reflection Texture used in the material.
  89732. * Should be author in a specific way for the best result (refer to the documentation).
  89733. */
  89734. _this.reflectionTexture = null;
  89735. /**
  89736. * Reflection Texture level of blur.
  89737. *
  89738. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  89739. * texture twice.
  89740. */
  89741. _this.reflectionBlur = 0;
  89742. /**
  89743. * Diffuse Texture used in the material.
  89744. * Should be author in a specific way for the best result (refer to the documentation).
  89745. */
  89746. _this.diffuseTexture = null;
  89747. _this._shadowLights = null;
  89748. /**
  89749. * Specify the list of lights casting shadow on the material.
  89750. * All scene shadow lights will be included if null.
  89751. */
  89752. _this.shadowLights = null;
  89753. /**
  89754. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  89755. * soft lighting on the background.
  89756. */
  89757. _this.shadowBlurScale = 1;
  89758. /**
  89759. * Helps adjusting the shadow to a softer level if required.
  89760. * 0 means black shadows and 1 means no shadows.
  89761. */
  89762. _this.shadowLevel = 0;
  89763. /**
  89764. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  89765. * It is usually zero but might be interesting to modify according to your setup.
  89766. */
  89767. _this.sceneCenter = BABYLON.Vector3.Zero();
  89768. /**
  89769. * This helps specifying that the material is falling off to the sky box at grazing angle.
  89770. * This helps ensuring a nice transition when the camera goes under the ground.
  89771. */
  89772. _this.opacityFresnel = true;
  89773. /**
  89774. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  89775. * This helps adding a mirror texture on the ground.
  89776. */
  89777. _this.reflectionFresnel = false;
  89778. /**
  89779. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  89780. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  89781. */
  89782. _this.reflectionFalloffDistance = 0.0;
  89783. /**
  89784. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  89785. */
  89786. _this.reflectionAmount = 1.0;
  89787. /**
  89788. * This specifies the weight of the reflection at grazing angle.
  89789. */
  89790. _this.reflectionReflectance0 = 0.05;
  89791. /**
  89792. * This specifies the weight of the reflection at a perpendicular point of view.
  89793. */
  89794. _this.reflectionReflectance90 = 0.5;
  89795. /**
  89796. * Helps to directly use the maps channels instead of their level.
  89797. */
  89798. _this.useRGBColor = true;
  89799. /**
  89800. * This helps reducing the banding effect that could occur on the background.
  89801. */
  89802. _this.enableNoise = false;
  89803. _this._fovMultiplier = 1.0;
  89804. /**
  89805. * Enable the FOV adjustment feature controlled by fovMultiplier.
  89806. * @type {boolean}
  89807. */
  89808. _this.useEquirectangularFOV = false;
  89809. _this._maxSimultaneousLights = 4;
  89810. /**
  89811. * Number of Simultaneous lights allowed on the material.
  89812. */
  89813. _this.maxSimultaneousLights = 4;
  89814. /**
  89815. * Keep track of the image processing observer to allow dispose and replace.
  89816. */
  89817. _this._imageProcessingObserver = null;
  89818. /**
  89819. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  89820. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  89821. */
  89822. _this.switchToBGR = false;
  89823. // Temp values kept as cache in the material.
  89824. _this._renderTargets = new BABYLON.SmartArray(16);
  89825. _this._reflectionControls = BABYLON.Vector4.Zero();
  89826. // Setup the default processing configuration to the scene.
  89827. _this._attachImageProcessingConfiguration(null);
  89828. _this.getRenderTargetTextures = function () {
  89829. _this._renderTargets.reset();
  89830. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  89831. _this._renderTargets.push(_this._diffuseTexture);
  89832. }
  89833. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  89834. _this._renderTargets.push(_this._reflectionTexture);
  89835. }
  89836. return _this._renderTargets;
  89837. };
  89838. return _this;
  89839. }
  89840. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  89841. /**
  89842. * Sets the reflection reflectance fresnel values according to the default standard
  89843. * empirically know to work well :-)
  89844. */
  89845. set: function (value) {
  89846. var reflectionWeight = value;
  89847. if (reflectionWeight < 0.5) {
  89848. reflectionWeight = reflectionWeight * 2.0;
  89849. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  89850. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  89851. }
  89852. else {
  89853. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  89854. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  89855. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  89856. }
  89857. },
  89858. enumerable: true,
  89859. configurable: true
  89860. });
  89861. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  89862. /**
  89863. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  89864. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  89865. * Recommended to be keep at 1.0 except for special cases.
  89866. */
  89867. get: function () {
  89868. return this._fovMultiplier;
  89869. },
  89870. set: function (value) {
  89871. if (isNaN(value)) {
  89872. value = 1.0;
  89873. }
  89874. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  89875. },
  89876. enumerable: true,
  89877. configurable: true
  89878. });
  89879. /**
  89880. * Attaches a new image processing configuration to the PBR Material.
  89881. * @param configuration (if null the scene configuration will be use)
  89882. */
  89883. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  89884. var _this = this;
  89885. if (configuration === this._imageProcessingConfiguration) {
  89886. return;
  89887. }
  89888. // Detaches observer.
  89889. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89890. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89891. }
  89892. // Pick the scene configuration if needed.
  89893. if (!configuration) {
  89894. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  89895. }
  89896. else {
  89897. this._imageProcessingConfiguration = configuration;
  89898. }
  89899. // Attaches observer.
  89900. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89901. _this._markAllSubMeshesAsImageProcessingDirty();
  89902. });
  89903. };
  89904. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  89905. /**
  89906. * Gets the image processing configuration used either in this material.
  89907. */
  89908. get: function () {
  89909. return this._imageProcessingConfiguration;
  89910. },
  89911. /**
  89912. * Sets the Default image processing configuration used either in the this material.
  89913. *
  89914. * If sets to null, the scene one is in use.
  89915. */
  89916. set: function (value) {
  89917. this._attachImageProcessingConfiguration(value);
  89918. // Ensure the effect will be rebuilt.
  89919. this._markAllSubMeshesAsTexturesDirty();
  89920. },
  89921. enumerable: true,
  89922. configurable: true
  89923. });
  89924. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  89925. /**
  89926. * Gets wether the color curves effect is enabled.
  89927. */
  89928. get: function () {
  89929. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89930. },
  89931. /**
  89932. * Sets wether the color curves effect is enabled.
  89933. */
  89934. set: function (value) {
  89935. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89936. },
  89937. enumerable: true,
  89938. configurable: true
  89939. });
  89940. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  89941. /**
  89942. * Gets wether the color grading effect is enabled.
  89943. */
  89944. get: function () {
  89945. return this.imageProcessingConfiguration.colorGradingEnabled;
  89946. },
  89947. /**
  89948. * Gets wether the color grading effect is enabled.
  89949. */
  89950. set: function (value) {
  89951. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89952. },
  89953. enumerable: true,
  89954. configurable: true
  89955. });
  89956. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  89957. /**
  89958. * Gets wether tonemapping is enabled or not.
  89959. */
  89960. get: function () {
  89961. return this._imageProcessingConfiguration.toneMappingEnabled;
  89962. },
  89963. /**
  89964. * Sets wether tonemapping is enabled or not
  89965. */
  89966. set: function (value) {
  89967. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89968. },
  89969. enumerable: true,
  89970. configurable: true
  89971. });
  89972. ;
  89973. ;
  89974. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  89975. /**
  89976. * The camera exposure used on this material.
  89977. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89978. * This corresponds to a photographic exposure.
  89979. */
  89980. get: function () {
  89981. return this._imageProcessingConfiguration.exposure;
  89982. },
  89983. /**
  89984. * The camera exposure used on this material.
  89985. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  89986. * This corresponds to a photographic exposure.
  89987. */
  89988. set: function (value) {
  89989. this._imageProcessingConfiguration.exposure = value;
  89990. },
  89991. enumerable: true,
  89992. configurable: true
  89993. });
  89994. ;
  89995. ;
  89996. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  89997. /**
  89998. * Gets The camera contrast used on this material.
  89999. */
  90000. get: function () {
  90001. return this._imageProcessingConfiguration.contrast;
  90002. },
  90003. /**
  90004. * Sets The camera contrast used on this material.
  90005. */
  90006. set: function (value) {
  90007. this._imageProcessingConfiguration.contrast = value;
  90008. },
  90009. enumerable: true,
  90010. configurable: true
  90011. });
  90012. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  90013. /**
  90014. * Gets the Color Grading 2D Lookup Texture.
  90015. */
  90016. get: function () {
  90017. return this._imageProcessingConfiguration.colorGradingTexture;
  90018. },
  90019. /**
  90020. * Sets the Color Grading 2D Lookup Texture.
  90021. */
  90022. set: function (value) {
  90023. this.imageProcessingConfiguration.colorGradingTexture = value;
  90024. },
  90025. enumerable: true,
  90026. configurable: true
  90027. });
  90028. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  90029. /**
  90030. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90031. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90032. * 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;
  90033. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90034. */
  90035. get: function () {
  90036. return this.imageProcessingConfiguration.colorCurves;
  90037. },
  90038. /**
  90039. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  90040. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  90041. * 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;
  90042. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  90043. */
  90044. set: function (value) {
  90045. this.imageProcessingConfiguration.colorCurves = value;
  90046. },
  90047. enumerable: true,
  90048. configurable: true
  90049. });
  90050. /**
  90051. * The entire material has been created in order to prevent overdraw.
  90052. * @returns false
  90053. */
  90054. BackgroundMaterial.prototype.needAlphaTesting = function () {
  90055. return true;
  90056. };
  90057. /**
  90058. * The entire material has been created in order to prevent overdraw.
  90059. * @returns true if blending is enable
  90060. */
  90061. BackgroundMaterial.prototype.needAlphaBlending = function () {
  90062. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  90063. };
  90064. /**
  90065. * Checks wether the material is ready to be rendered for a given mesh.
  90066. * @param mesh The mesh to render
  90067. * @param subMesh The submesh to check against
  90068. * @param useInstances Specify wether or not the material is used with instances
  90069. * @returns true if all the dependencies are ready (Textures, Effects...)
  90070. */
  90071. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  90072. var _this = this;
  90073. if (useInstances === void 0) { useInstances = false; }
  90074. if (subMesh.effect && this.isFrozen) {
  90075. if (this._wasPreviouslyReady) {
  90076. return true;
  90077. }
  90078. }
  90079. if (!subMesh._materialDefines) {
  90080. subMesh._materialDefines = new BackgroundMaterialDefines();
  90081. }
  90082. var scene = this.getScene();
  90083. var defines = subMesh._materialDefines;
  90084. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  90085. if (defines._renderId === scene.getRenderId()) {
  90086. return true;
  90087. }
  90088. }
  90089. var engine = scene.getEngine();
  90090. // Lights
  90091. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  90092. defines._needNormals = true;
  90093. // Textures
  90094. if (defines._areTexturesDirty) {
  90095. defines._needUVs = false;
  90096. if (scene.texturesEnabled) {
  90097. if (scene.getEngine().getCaps().textureLOD) {
  90098. defines.TEXTURELODSUPPORT = true;
  90099. }
  90100. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90101. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  90102. return false;
  90103. }
  90104. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  90105. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  90106. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  90107. defines.OPACITYFRESNEL = this._opacityFresnel;
  90108. }
  90109. else {
  90110. defines.DIFFUSE = false;
  90111. defines.DIFFUSEHASALPHA = false;
  90112. defines.GAMMADIFFUSE = false;
  90113. defines.OPACITYFRESNEL = false;
  90114. }
  90115. var reflectionTexture = this._reflectionTexture;
  90116. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90117. if (!reflectionTexture.isReadyOrNotBlocking()) {
  90118. return false;
  90119. }
  90120. defines.REFLECTION = true;
  90121. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  90122. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  90123. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  90124. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  90125. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  90126. defines.REFLECTIONBGR = this.switchToBGR;
  90127. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  90128. defines.INVERTCUBICMAP = true;
  90129. }
  90130. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  90131. switch (reflectionTexture.coordinatesMode) {
  90132. case BABYLON.Texture.CUBIC_MODE:
  90133. case BABYLON.Texture.INVCUBIC_MODE:
  90134. defines.REFLECTIONMAP_CUBIC = true;
  90135. break;
  90136. case BABYLON.Texture.EXPLICIT_MODE:
  90137. defines.REFLECTIONMAP_EXPLICIT = true;
  90138. break;
  90139. case BABYLON.Texture.PLANAR_MODE:
  90140. defines.REFLECTIONMAP_PLANAR = true;
  90141. break;
  90142. case BABYLON.Texture.PROJECTION_MODE:
  90143. defines.REFLECTIONMAP_PROJECTION = true;
  90144. break;
  90145. case BABYLON.Texture.SKYBOX_MODE:
  90146. defines.REFLECTIONMAP_SKYBOX = true;
  90147. break;
  90148. case BABYLON.Texture.SPHERICAL_MODE:
  90149. defines.REFLECTIONMAP_SPHERICAL = true;
  90150. break;
  90151. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  90152. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  90153. break;
  90154. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  90155. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  90156. break;
  90157. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  90158. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  90159. break;
  90160. }
  90161. if (this.reflectionFresnel) {
  90162. defines.REFLECTIONFRESNEL = true;
  90163. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  90164. this._reflectionControls.x = this.reflectionAmount;
  90165. this._reflectionControls.y = this.reflectionReflectance0;
  90166. this._reflectionControls.z = this.reflectionReflectance90;
  90167. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  90168. }
  90169. else {
  90170. defines.REFLECTIONFRESNEL = false;
  90171. defines.REFLECTIONFALLOFF = false;
  90172. }
  90173. }
  90174. else {
  90175. defines.REFLECTION = false;
  90176. defines.REFLECTIONFALLOFF = false;
  90177. defines.REFLECTIONBLUR = false;
  90178. defines.REFLECTIONMAP_3D = false;
  90179. defines.REFLECTIONMAP_SPHERICAL = false;
  90180. defines.REFLECTIONMAP_PLANAR = false;
  90181. defines.REFLECTIONMAP_CUBIC = false;
  90182. defines.REFLECTIONMAP_PROJECTION = false;
  90183. defines.REFLECTIONMAP_SKYBOX = false;
  90184. defines.REFLECTIONMAP_EXPLICIT = false;
  90185. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90186. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90187. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90188. defines.INVERTCUBICMAP = false;
  90189. defines.REFLECTIONMAP_OPPOSITEZ = false;
  90190. defines.LODINREFLECTIONALPHA = false;
  90191. defines.GAMMAREFLECTION = false;
  90192. }
  90193. }
  90194. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  90195. defines.USERGBCOLOR = this._useRGBColor;
  90196. defines.NOISE = this._enableNoise;
  90197. }
  90198. if (defines._areImageProcessingDirty) {
  90199. if (!this._imageProcessingConfiguration.isReady()) {
  90200. return false;
  90201. }
  90202. this._imageProcessingConfiguration.prepareDefines(defines);
  90203. }
  90204. // Misc.
  90205. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  90206. // Values that need to be evaluated on every frame
  90207. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  90208. // Attribs
  90209. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  90210. if (mesh) {
  90211. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90212. mesh.createNormals(true);
  90213. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  90214. }
  90215. }
  90216. }
  90217. // Get correct effect
  90218. if (defines.isDirty) {
  90219. defines.markAsProcessed();
  90220. scene.resetCachedMaterial();
  90221. // Fallbacks
  90222. var fallbacks = new BABYLON.EffectFallbacks();
  90223. if (defines.FOG) {
  90224. fallbacks.addFallback(0, "FOG");
  90225. }
  90226. if (defines.POINTSIZE) {
  90227. fallbacks.addFallback(1, "POINTSIZE");
  90228. }
  90229. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  90230. if (defines.NUM_BONE_INFLUENCERS > 0) {
  90231. fallbacks.addCPUSkinningFallback(0, mesh);
  90232. }
  90233. //Attributes
  90234. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90235. if (defines.NORMAL) {
  90236. attribs.push(BABYLON.VertexBuffer.NormalKind);
  90237. }
  90238. if (defines.UV1) {
  90239. attribs.push(BABYLON.VertexBuffer.UVKind);
  90240. }
  90241. if (defines.UV2) {
  90242. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90243. }
  90244. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  90245. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  90246. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  90247. "vFogInfos", "vFogColor", "pointSize",
  90248. "vClipPlane", "mBones",
  90249. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  90250. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  90251. "shadowLevel", "alpha",
  90252. "vBackgroundCenter", "vReflectionControl",
  90253. "vDiffuseInfos", "diffuseMatrix",
  90254. ];
  90255. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  90256. var uniformBuffers = ["Material", "Scene"];
  90257. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  90258. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  90259. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  90260. uniformsNames: uniforms,
  90261. uniformBuffersNames: uniformBuffers,
  90262. samplers: samplers,
  90263. defines: defines,
  90264. maxSimultaneousLights: this._maxSimultaneousLights
  90265. });
  90266. var onCompiled = function (effect) {
  90267. if (_this.onCompiled) {
  90268. _this.onCompiled(effect);
  90269. }
  90270. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  90271. };
  90272. var join = defines.toString();
  90273. subMesh.setEffect(scene.getEngine().createEffect("background", {
  90274. attributes: attribs,
  90275. uniformsNames: uniforms,
  90276. uniformBuffersNames: uniformBuffers,
  90277. samplers: samplers,
  90278. defines: join,
  90279. fallbacks: fallbacks,
  90280. onCompiled: onCompiled,
  90281. onError: this.onError,
  90282. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  90283. }, engine), defines);
  90284. this.buildUniformLayout();
  90285. }
  90286. if (!subMesh.effect || !subMesh.effect.isReady()) {
  90287. return false;
  90288. }
  90289. defines._renderId = scene.getRenderId();
  90290. this._wasPreviouslyReady = true;
  90291. return true;
  90292. };
  90293. /**
  90294. * Build the uniform buffer used in the material.
  90295. */
  90296. BackgroundMaterial.prototype.buildUniformLayout = function () {
  90297. // Order is important !
  90298. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  90299. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  90300. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  90301. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  90302. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  90303. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  90304. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  90305. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  90306. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  90307. this._uniformBuffer.addUniform("pointSize", 1);
  90308. this._uniformBuffer.addUniform("shadowLevel", 1);
  90309. this._uniformBuffer.addUniform("alpha", 1);
  90310. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  90311. this._uniformBuffer.addUniform("vReflectionControl", 4);
  90312. this._uniformBuffer.create();
  90313. };
  90314. /**
  90315. * Unbind the material.
  90316. */
  90317. BackgroundMaterial.prototype.unbind = function () {
  90318. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  90319. this._uniformBuffer.setTexture("diffuseSampler", null);
  90320. }
  90321. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  90322. this._uniformBuffer.setTexture("reflectionSampler", null);
  90323. }
  90324. _super.prototype.unbind.call(this);
  90325. };
  90326. /**
  90327. * Bind only the world matrix to the material.
  90328. * @param world The world matrix to bind.
  90329. */
  90330. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  90331. this._activeEffect.setMatrix("world", world);
  90332. };
  90333. /**
  90334. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  90335. * @param world The world matrix to bind.
  90336. * @param subMesh The submesh to bind for.
  90337. */
  90338. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  90339. var scene = this.getScene();
  90340. var defines = subMesh._materialDefines;
  90341. if (!defines) {
  90342. return;
  90343. }
  90344. var effect = subMesh.effect;
  90345. if (!effect) {
  90346. return;
  90347. }
  90348. this._activeEffect = effect;
  90349. // Matrices
  90350. this.bindOnlyWorldMatrix(world);
  90351. // Bones
  90352. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  90353. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  90354. if (mustRebind) {
  90355. this._uniformBuffer.bindToEffect(effect, "Material");
  90356. this.bindViewProjection(effect);
  90357. var reflectionTexture = this._reflectionTexture;
  90358. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  90359. // Texture uniforms
  90360. if (scene.texturesEnabled) {
  90361. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90362. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  90363. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  90364. }
  90365. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90366. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  90367. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  90368. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  90369. }
  90370. }
  90371. if (this.shadowLevel > 0) {
  90372. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  90373. }
  90374. this._uniformBuffer.updateFloat("alpha", this.alpha);
  90375. // Point size
  90376. if (this.pointsCloud) {
  90377. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  90378. }
  90379. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  90380. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  90381. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  90382. }
  90383. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  90384. // Textures
  90385. if (scene.texturesEnabled) {
  90386. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  90387. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  90388. }
  90389. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  90390. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  90391. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90392. }
  90393. else if (!defines.REFLECTIONBLUR) {
  90394. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  90395. }
  90396. else {
  90397. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  90398. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  90399. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  90400. }
  90401. if (defines.REFLECTIONFRESNEL) {
  90402. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  90403. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  90404. }
  90405. }
  90406. }
  90407. // Clip plane
  90408. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  90409. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  90410. }
  90411. if (mustRebind || !this.isFrozen) {
  90412. if (scene.lightsEnabled) {
  90413. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  90414. }
  90415. // View
  90416. this.bindView(effect);
  90417. // Fog
  90418. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  90419. // image processing
  90420. this._imageProcessingConfiguration.bind(this._activeEffect);
  90421. }
  90422. this._uniformBuffer.update();
  90423. this._afterBind(mesh);
  90424. };
  90425. /**
  90426. * Dispose the material.
  90427. * @param forceDisposeEffect Force disposal of the associated effect.
  90428. * @param forceDisposeTextures Force disposal of the associated textures.
  90429. */
  90430. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  90431. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  90432. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  90433. if (forceDisposeTextures) {
  90434. if (this.diffuseTexture) {
  90435. this.diffuseTexture.dispose();
  90436. }
  90437. if (this.reflectionTexture) {
  90438. this.reflectionTexture.dispose();
  90439. }
  90440. }
  90441. this._renderTargets.dispose();
  90442. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90443. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90444. }
  90445. _super.prototype.dispose.call(this, forceDisposeEffect);
  90446. };
  90447. /**
  90448. * Clones the material.
  90449. * @param name The cloned name.
  90450. * @returns The cloned material.
  90451. */
  90452. BackgroundMaterial.prototype.clone = function (name) {
  90453. var _this = this;
  90454. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  90455. };
  90456. /**
  90457. * Serializes the current material to its JSON representation.
  90458. * @returns The JSON representation.
  90459. */
  90460. BackgroundMaterial.prototype.serialize = function () {
  90461. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  90462. serializationObject.customType = "BABYLON.BackgroundMaterial";
  90463. return serializationObject;
  90464. };
  90465. /**
  90466. * Gets the class name of the material
  90467. * @returns "BackgroundMaterial"
  90468. */
  90469. BackgroundMaterial.prototype.getClassName = function () {
  90470. return "BackgroundMaterial";
  90471. };
  90472. /**
  90473. * Parse a JSON input to create back a background material.
  90474. * @param source The JSON data to parse
  90475. * @param scene The scene to create the parsed material in
  90476. * @param rootUrl The root url of the assets the material depends upon
  90477. * @returns the instantiated BackgroundMaterial.
  90478. */
  90479. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  90480. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  90481. };
  90482. /**
  90483. * Standard reflectance value at parallel view angle.
  90484. */
  90485. BackgroundMaterial.StandardReflectance0 = 0.05;
  90486. /**
  90487. * Standard reflectance value at grazing angle.
  90488. */
  90489. BackgroundMaterial.StandardReflectance90 = 0.5;
  90490. __decorate([
  90491. BABYLON.serializeAsColor3()
  90492. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  90493. __decorate([
  90494. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90495. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  90496. __decorate([
  90497. BABYLON.serialize()
  90498. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  90499. __decorate([
  90500. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90501. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  90502. __decorate([
  90503. BABYLON.serializeAsColor3()
  90504. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  90505. __decorate([
  90506. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90507. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  90508. __decorate([
  90509. BABYLON.serialize()
  90510. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  90511. __decorate([
  90512. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90513. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  90514. __decorate([
  90515. BABYLON.serializeAsColor3()
  90516. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  90517. __decorate([
  90518. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90519. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  90520. __decorate([
  90521. BABYLON.serialize()
  90522. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  90523. __decorate([
  90524. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  90525. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  90526. __decorate([
  90527. BABYLON.serializeAsTexture()
  90528. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  90529. __decorate([
  90530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90531. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  90532. __decorate([
  90533. BABYLON.serialize()
  90534. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  90535. __decorate([
  90536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90537. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  90538. __decorate([
  90539. BABYLON.serializeAsTexture()
  90540. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  90541. __decorate([
  90542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90543. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  90544. __decorate([
  90545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90546. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  90547. __decorate([
  90548. BABYLON.serialize()
  90549. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  90550. __decorate([
  90551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90552. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  90553. __decorate([
  90554. BABYLON.serialize()
  90555. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  90556. __decorate([
  90557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90558. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  90559. __decorate([
  90560. BABYLON.serializeAsVector3()
  90561. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  90562. __decorate([
  90563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90564. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  90565. __decorate([
  90566. BABYLON.serialize()
  90567. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  90568. __decorate([
  90569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90570. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  90571. __decorate([
  90572. BABYLON.serialize()
  90573. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  90574. __decorate([
  90575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90576. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  90577. __decorate([
  90578. BABYLON.serialize()
  90579. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  90580. __decorate([
  90581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90582. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  90583. __decorate([
  90584. BABYLON.serialize()
  90585. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  90586. __decorate([
  90587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90588. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  90589. __decorate([
  90590. BABYLON.serialize()
  90591. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  90592. __decorate([
  90593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90594. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  90595. __decorate([
  90596. BABYLON.serialize()
  90597. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  90598. __decorate([
  90599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90600. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  90601. __decorate([
  90602. BABYLON.serialize()
  90603. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  90604. __decorate([
  90605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90606. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  90607. __decorate([
  90608. BABYLON.serialize()
  90609. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  90610. __decorate([
  90611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90612. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  90613. __decorate([
  90614. BABYLON.serialize()
  90615. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  90616. __decorate([
  90617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  90618. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  90619. __decorate([
  90620. BABYLON.serializeAsImageProcessingConfiguration()
  90621. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  90622. return BackgroundMaterial;
  90623. }(BABYLON.PushMaterial));
  90624. BABYLON.BackgroundMaterial = BackgroundMaterial;
  90625. })(BABYLON || (BABYLON = {}));
  90626. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  90627. "use strict";
  90628. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90629. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90630. s = arguments[i];
  90631. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90632. t[p] = s[p];
  90633. }
  90634. return t;
  90635. };
  90636. var BABYLON;
  90637. (function (BABYLON) {
  90638. /**
  90639. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  90640. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  90641. * It also helps with the default setup of your imageProcessing configuration.
  90642. */
  90643. var EnvironmentHelper = /** @class */ (function () {
  90644. /**
  90645. * constructor
  90646. * @param options
  90647. * @param scene The scene to add the material to
  90648. */
  90649. function EnvironmentHelper(options, scene) {
  90650. var _this = this;
  90651. this._errorHandler = function (message, exception) {
  90652. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  90653. };
  90654. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  90655. this._scene = scene;
  90656. this.onErrorObservable = new BABYLON.Observable();
  90657. this._setupBackground();
  90658. this._setupImageProcessing();
  90659. }
  90660. /**
  90661. * Creates the default options for the helper.
  90662. */
  90663. EnvironmentHelper._getDefaultOptions = function () {
  90664. return {
  90665. createGround: true,
  90666. groundSize: 15,
  90667. groundTexture: this._groundTextureCDNUrl,
  90668. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90669. groundOpacity: 0.9,
  90670. enableGroundShadow: true,
  90671. groundShadowLevel: 0.5,
  90672. enableGroundMirror: false,
  90673. groundMirrorSizeRatio: 0.3,
  90674. groundMirrorBlurKernel: 64,
  90675. groundMirrorAmount: 1,
  90676. groundMirrorFresnelWeight: 1,
  90677. groundMirrorFallOffDistance: 0,
  90678. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  90679. groundYBias: 0.00001,
  90680. createSkybox: true,
  90681. skyboxSize: 20,
  90682. skyboxTexture: this._skyboxTextureCDNUrl,
  90683. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  90684. backgroundYRotation: 0,
  90685. sizeAuto: true,
  90686. rootPosition: BABYLON.Vector3.Zero(),
  90687. setupImageProcessing: true,
  90688. environmentTexture: this._environmentTextureCDNUrl,
  90689. cameraExposure: 0.8,
  90690. cameraContrast: 1.2,
  90691. toneMappingEnabled: true,
  90692. };
  90693. };
  90694. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  90695. /**
  90696. * Gets the root mesh created by the helper.
  90697. */
  90698. get: function () {
  90699. return this._rootMesh;
  90700. },
  90701. enumerable: true,
  90702. configurable: true
  90703. });
  90704. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  90705. /**
  90706. * Gets the skybox created by the helper.
  90707. */
  90708. get: function () {
  90709. return this._skybox;
  90710. },
  90711. enumerable: true,
  90712. configurable: true
  90713. });
  90714. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  90715. /**
  90716. * Gets the skybox texture created by the helper.
  90717. */
  90718. get: function () {
  90719. return this._skyboxTexture;
  90720. },
  90721. enumerable: true,
  90722. configurable: true
  90723. });
  90724. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  90725. /**
  90726. * Gets the skybox material created by the helper.
  90727. */
  90728. get: function () {
  90729. return this._skyboxMaterial;
  90730. },
  90731. enumerable: true,
  90732. configurable: true
  90733. });
  90734. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  90735. /**
  90736. * Gets the ground mesh created by the helper.
  90737. */
  90738. get: function () {
  90739. return this._ground;
  90740. },
  90741. enumerable: true,
  90742. configurable: true
  90743. });
  90744. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  90745. /**
  90746. * Gets the ground texture created by the helper.
  90747. */
  90748. get: function () {
  90749. return this._groundTexture;
  90750. },
  90751. enumerable: true,
  90752. configurable: true
  90753. });
  90754. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  90755. /**
  90756. * Gets the ground mirror created by the helper.
  90757. */
  90758. get: function () {
  90759. return this._groundMirror;
  90760. },
  90761. enumerable: true,
  90762. configurable: true
  90763. });
  90764. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  90765. /**
  90766. * Gets the ground mirror render list to helps pushing the meshes
  90767. * you wish in the ground reflection.
  90768. */
  90769. get: function () {
  90770. if (this._groundMirror) {
  90771. return this._groundMirror.renderList;
  90772. }
  90773. return null;
  90774. },
  90775. enumerable: true,
  90776. configurable: true
  90777. });
  90778. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  90779. /**
  90780. * Gets the ground material created by the helper.
  90781. */
  90782. get: function () {
  90783. return this._groundMaterial;
  90784. },
  90785. enumerable: true,
  90786. configurable: true
  90787. });
  90788. /**
  90789. * Updates the background according to the new options
  90790. * @param options
  90791. */
  90792. EnvironmentHelper.prototype.updateOptions = function (options) {
  90793. var newOptions = __assign({}, this._options, options);
  90794. if (this._ground && !newOptions.createGround) {
  90795. this._ground.dispose();
  90796. this._ground = null;
  90797. }
  90798. if (this._groundMaterial && !newOptions.createGround) {
  90799. this._groundMaterial.dispose();
  90800. this._groundMaterial = null;
  90801. }
  90802. if (this._groundTexture) {
  90803. if (this._options.groundTexture != newOptions.groundTexture) {
  90804. this._groundTexture.dispose();
  90805. this._groundTexture = null;
  90806. }
  90807. }
  90808. if (this._skybox && !newOptions.createSkybox) {
  90809. this._skybox.dispose();
  90810. this._skybox = null;
  90811. }
  90812. if (this._skyboxMaterial && !newOptions.createSkybox) {
  90813. this._skyboxMaterial.dispose();
  90814. this._skyboxMaterial = null;
  90815. }
  90816. if (this._skyboxTexture) {
  90817. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  90818. this._skyboxTexture.dispose();
  90819. this._skyboxTexture = null;
  90820. }
  90821. }
  90822. if (this._groundMirror && !newOptions.enableGroundMirror) {
  90823. this._groundMirror.dispose();
  90824. this._groundMirror = null;
  90825. }
  90826. if (this._scene.environmentTexture) {
  90827. if (this._options.environmentTexture != newOptions.environmentTexture) {
  90828. this._scene.environmentTexture.dispose();
  90829. }
  90830. }
  90831. this._options = newOptions;
  90832. this._setupBackground();
  90833. this._setupImageProcessing();
  90834. };
  90835. /**
  90836. * Sets the primary color of all the available elements.
  90837. * @param color
  90838. */
  90839. EnvironmentHelper.prototype.setMainColor = function (color) {
  90840. if (this.groundMaterial) {
  90841. this.groundMaterial.primaryColor = color;
  90842. }
  90843. if (this.skyboxMaterial) {
  90844. this.skyboxMaterial.primaryColor = color;
  90845. }
  90846. if (this.groundMirror) {
  90847. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  90848. }
  90849. };
  90850. /**
  90851. * Setup the image processing according to the specified options.
  90852. */
  90853. EnvironmentHelper.prototype._setupImageProcessing = function () {
  90854. if (this._options.setupImageProcessing) {
  90855. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  90856. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  90857. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  90858. this._setupEnvironmentTexture();
  90859. }
  90860. };
  90861. /**
  90862. * Setup the environment texture according to the specified options.
  90863. */
  90864. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  90865. if (this._scene.environmentTexture) {
  90866. return;
  90867. }
  90868. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  90869. this._scene.environmentTexture = this._options.environmentTexture;
  90870. return;
  90871. }
  90872. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  90873. this._scene.environmentTexture = environmentTexture;
  90874. };
  90875. /**
  90876. * Setup the background according to the specified options.
  90877. */
  90878. EnvironmentHelper.prototype._setupBackground = function () {
  90879. if (!this._rootMesh) {
  90880. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  90881. }
  90882. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  90883. var sceneSize = this._getSceneSize();
  90884. if (this._options.createGround) {
  90885. this._setupGround(sceneSize);
  90886. this._setupGroundMaterial();
  90887. this._setupGroundDiffuseTexture();
  90888. if (this._options.enableGroundMirror) {
  90889. this._setupGroundMirrorTexture(sceneSize);
  90890. }
  90891. this._setupMirrorInGroundMaterial();
  90892. }
  90893. if (this._options.createSkybox) {
  90894. this._setupSkybox(sceneSize);
  90895. this._setupSkyboxMaterial();
  90896. this._setupSkyboxReflectionTexture();
  90897. }
  90898. this._rootMesh.position.x = sceneSize.rootPosition.x;
  90899. this._rootMesh.position.z = sceneSize.rootPosition.z;
  90900. this._rootMesh.position.y = sceneSize.rootPosition.y;
  90901. };
  90902. /**
  90903. * Get the scene sizes according to the setup.
  90904. */
  90905. EnvironmentHelper.prototype._getSceneSize = function () {
  90906. var _this = this;
  90907. var groundSize = this._options.groundSize;
  90908. var skyboxSize = this._options.skyboxSize;
  90909. var rootPosition = this._options.rootPosition;
  90910. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  90911. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90912. }
  90913. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  90914. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  90915. });
  90916. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  90917. if (this._options.sizeAuto) {
  90918. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  90919. this._scene.activeCamera.upperRadiusLimit) {
  90920. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  90921. skyboxSize = groundSize;
  90922. }
  90923. var sceneDiagonalLenght = sceneDiagonal.length();
  90924. if (sceneDiagonalLenght > groundSize) {
  90925. groundSize = sceneDiagonalLenght * 2;
  90926. skyboxSize = groundSize;
  90927. }
  90928. // 10 % bigger.
  90929. groundSize *= 1.1;
  90930. skyboxSize *= 1.5;
  90931. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  90932. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  90933. }
  90934. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  90935. };
  90936. /**
  90937. * Setup the ground according to the specified options.
  90938. */
  90939. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  90940. var _this = this;
  90941. if (!this._ground) {
  90942. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  90943. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  90944. this._ground.parent = this._rootMesh;
  90945. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  90946. }
  90947. this._ground.receiveShadows = this._options.enableGroundShadow;
  90948. };
  90949. /**
  90950. * Setup the ground material according to the specified options.
  90951. */
  90952. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  90953. if (!this._groundMaterial) {
  90954. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  90955. }
  90956. this._groundMaterial.alpha = this._options.groundOpacity;
  90957. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  90958. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  90959. this._groundMaterial.primaryLevel = 1;
  90960. this._groundMaterial.primaryColor = this._options.groundColor;
  90961. this._groundMaterial.secondaryLevel = 0;
  90962. this._groundMaterial.tertiaryLevel = 0;
  90963. this._groundMaterial.useRGBColor = false;
  90964. this._groundMaterial.enableNoise = true;
  90965. if (this._ground) {
  90966. this._ground.material = this._groundMaterial;
  90967. }
  90968. };
  90969. /**
  90970. * Setup the ground diffuse texture according to the specified options.
  90971. */
  90972. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  90973. if (!this._groundMaterial) {
  90974. return;
  90975. }
  90976. if (this._groundTexture) {
  90977. return;
  90978. }
  90979. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  90980. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  90981. return;
  90982. }
  90983. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  90984. diffuseTexture.gammaSpace = false;
  90985. diffuseTexture.hasAlpha = true;
  90986. this._groundMaterial.diffuseTexture = diffuseTexture;
  90987. };
  90988. /**
  90989. * Setup the ground mirror texture according to the specified options.
  90990. */
  90991. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  90992. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90993. if (!this._groundMirror) {
  90994. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  90995. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  90996. this._groundMirror.anisotropicFilteringLevel = 1;
  90997. this._groundMirror.wrapU = wrapping;
  90998. this._groundMirror.wrapV = wrapping;
  90999. this._groundMirror.gammaSpace = false;
  91000. if (this._groundMirror.renderList) {
  91001. for (var i = 0; i < this._scene.meshes.length; i++) {
  91002. var mesh = this._scene.meshes[i];
  91003. if (mesh !== this._ground &&
  91004. mesh !== this._skybox &&
  91005. mesh !== this._rootMesh) {
  91006. this._groundMirror.renderList.push(mesh);
  91007. }
  91008. }
  91009. }
  91010. }
  91011. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  91012. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  91013. };
  91014. /**
  91015. * Setup the ground to receive the mirror texture.
  91016. */
  91017. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  91018. if (this._groundMaterial) {
  91019. this._groundMaterial.reflectionTexture = this._groundMirror;
  91020. this._groundMaterial.reflectionFresnel = true;
  91021. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  91022. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  91023. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  91024. }
  91025. };
  91026. /**
  91027. * Setup the skybox according to the specified options.
  91028. */
  91029. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  91030. var _this = this;
  91031. if (!this._skybox) {
  91032. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  91033. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  91034. }
  91035. this._skybox.parent = this._rootMesh;
  91036. };
  91037. /**
  91038. * Setup the skybox material according to the specified options.
  91039. */
  91040. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  91041. if (!this._skybox) {
  91042. return;
  91043. }
  91044. if (!this._skyboxMaterial) {
  91045. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  91046. }
  91047. this._skyboxMaterial.useRGBColor = false;
  91048. this._skyboxMaterial.primaryLevel = 1;
  91049. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  91050. this._skyboxMaterial.secondaryLevel = 0;
  91051. this._skyboxMaterial.tertiaryLevel = 0;
  91052. this._skyboxMaterial.enableNoise = true;
  91053. this._skybox.material = this._skyboxMaterial;
  91054. };
  91055. /**
  91056. * Setup the skybox reflection texture according to the specified options.
  91057. */
  91058. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  91059. if (!this._skyboxMaterial) {
  91060. return;
  91061. }
  91062. if (this._skyboxTexture) {
  91063. return;
  91064. }
  91065. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  91066. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91067. return;
  91068. }
  91069. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  91070. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  91071. this._skyboxTexture.gammaSpace = false;
  91072. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  91073. };
  91074. /**
  91075. * Dispose all the elements created by the Helper.
  91076. */
  91077. EnvironmentHelper.prototype.dispose = function () {
  91078. if (this._groundMaterial) {
  91079. this._groundMaterial.dispose(true, true);
  91080. }
  91081. if (this._skyboxMaterial) {
  91082. this._skyboxMaterial.dispose(true, true);
  91083. }
  91084. this._rootMesh.dispose(false);
  91085. };
  91086. /**
  91087. * Default ground texture URL.
  91088. */
  91089. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  91090. /**
  91091. * Default skybox texture URL.
  91092. */
  91093. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  91094. /**
  91095. * Default environment texture URL.
  91096. */
  91097. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  91098. return EnvironmentHelper;
  91099. }());
  91100. BABYLON.EnvironmentHelper = EnvironmentHelper;
  91101. })(BABYLON || (BABYLON = {}));
  91102. //# sourceMappingURL=babylon.environmentHelper.js.map
  91103. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\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);\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=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\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\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#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\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\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#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 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);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\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 vec3 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.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  91104. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(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 computeShadowWithPoissonSampling(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#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(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#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,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#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  91105. "use strict";
  91106. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  91107. var BABYLON;
  91108. (function (BABYLON) {
  91109. var GridMaterialDefines = /** @class */ (function (_super) {
  91110. __extends(GridMaterialDefines, _super);
  91111. function GridMaterialDefines() {
  91112. var _this = _super.call(this) || this;
  91113. _this.TRANSPARENT = false;
  91114. _this.FOG = false;
  91115. _this.PREMULTIPLYALPHA = false;
  91116. _this.rebuild();
  91117. return _this;
  91118. }
  91119. return GridMaterialDefines;
  91120. }(BABYLON.MaterialDefines));
  91121. /**
  91122. * The grid materials allows you to wrap any shape with a grid.
  91123. * Colors are customizable.
  91124. */
  91125. var GridMaterial = /** @class */ (function (_super) {
  91126. __extends(GridMaterial, _super);
  91127. /**
  91128. * constructor
  91129. * @param name The name given to the material in order to identify it afterwards.
  91130. * @param scene The scene the material is used in.
  91131. */
  91132. function GridMaterial(name, scene) {
  91133. var _this = _super.call(this, name, scene) || this;
  91134. /**
  91135. * Main color of the grid (e.g. between lines)
  91136. */
  91137. _this.mainColor = BABYLON.Color3.Black();
  91138. /**
  91139. * Color of the grid lines.
  91140. */
  91141. _this.lineColor = BABYLON.Color3.Teal();
  91142. /**
  91143. * The scale of the grid compared to unit.
  91144. */
  91145. _this.gridRatio = 1.0;
  91146. /**
  91147. * Allows setting an offset for the grid lines.
  91148. */
  91149. _this.gridOffset = BABYLON.Vector3.Zero();
  91150. /**
  91151. * The frequency of thicker lines.
  91152. */
  91153. _this.majorUnitFrequency = 10;
  91154. /**
  91155. * The visibility of minor units in the grid.
  91156. */
  91157. _this.minorUnitVisibility = 0.33;
  91158. /**
  91159. * The grid opacity outside of the lines.
  91160. */
  91161. _this.opacity = 1.0;
  91162. /**
  91163. * Determine RBG output is premultiplied by alpha value.
  91164. */
  91165. _this.preMultiplyAlpha = false;
  91166. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  91167. return _this;
  91168. }
  91169. /**
  91170. * Returns wehter or not the grid requires alpha blending.
  91171. */
  91172. GridMaterial.prototype.needAlphaBlending = function () {
  91173. return this.opacity < 1.0;
  91174. };
  91175. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  91176. return this.needAlphaBlending();
  91177. };
  91178. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91179. if (this.isFrozen) {
  91180. if (this._wasPreviouslyReady && subMesh.effect) {
  91181. return true;
  91182. }
  91183. }
  91184. if (!subMesh._materialDefines) {
  91185. subMesh._materialDefines = new GridMaterialDefines();
  91186. }
  91187. var defines = subMesh._materialDefines;
  91188. var scene = this.getScene();
  91189. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91190. if (this._renderId === scene.getRenderId()) {
  91191. return true;
  91192. }
  91193. }
  91194. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  91195. defines.TRANSPARENT = !defines.TRANSPARENT;
  91196. defines.markAsUnprocessed();
  91197. }
  91198. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  91199. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  91200. defines.markAsUnprocessed();
  91201. }
  91202. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  91203. // Get correct effect
  91204. if (defines.isDirty) {
  91205. defines.markAsProcessed();
  91206. scene.resetCachedMaterial();
  91207. // Attributes
  91208. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91209. // Defines
  91210. var join = defines.toString();
  91211. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  91212. }
  91213. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91214. return false;
  91215. }
  91216. this._renderId = scene.getRenderId();
  91217. this._wasPreviouslyReady = true;
  91218. return true;
  91219. };
  91220. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91221. var scene = this.getScene();
  91222. var defines = subMesh._materialDefines;
  91223. if (!defines) {
  91224. return;
  91225. }
  91226. var effect = subMesh.effect;
  91227. if (!effect) {
  91228. return;
  91229. }
  91230. this._activeEffect = effect;
  91231. // Matrices
  91232. this.bindOnlyWorldMatrix(world);
  91233. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  91234. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  91235. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  91236. // Uniforms
  91237. if (this._mustRebind(scene, effect)) {
  91238. this._activeEffect.setColor3("mainColor", this.mainColor);
  91239. this._activeEffect.setColor3("lineColor", this.lineColor);
  91240. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  91241. this._gridControl.x = this.gridRatio;
  91242. this._gridControl.y = Math.round(this.majorUnitFrequency);
  91243. this._gridControl.z = this.minorUnitVisibility;
  91244. this._gridControl.w = this.opacity;
  91245. this._activeEffect.setVector4("gridControl", this._gridControl);
  91246. }
  91247. // Fog
  91248. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91249. this._afterBind(mesh, this._activeEffect);
  91250. };
  91251. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  91252. _super.prototype.dispose.call(this, forceDisposeEffect);
  91253. };
  91254. GridMaterial.prototype.clone = function (name) {
  91255. var _this = this;
  91256. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  91257. };
  91258. GridMaterial.prototype.serialize = function () {
  91259. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91260. serializationObject.customType = "BABYLON.GridMaterial";
  91261. return serializationObject;
  91262. };
  91263. GridMaterial.prototype.getClassName = function () {
  91264. return "GridMaterial";
  91265. };
  91266. GridMaterial.Parse = function (source, scene, rootUrl) {
  91267. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  91268. };
  91269. __decorate([
  91270. BABYLON.serializeAsColor3()
  91271. ], GridMaterial.prototype, "mainColor", void 0);
  91272. __decorate([
  91273. BABYLON.serializeAsColor3()
  91274. ], GridMaterial.prototype, "lineColor", void 0);
  91275. __decorate([
  91276. BABYLON.serialize()
  91277. ], GridMaterial.prototype, "gridRatio", void 0);
  91278. __decorate([
  91279. BABYLON.serializeAsColor3()
  91280. ], GridMaterial.prototype, "gridOffset", void 0);
  91281. __decorate([
  91282. BABYLON.serialize()
  91283. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  91284. __decorate([
  91285. BABYLON.serialize()
  91286. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  91287. __decorate([
  91288. BABYLON.serialize()
  91289. ], GridMaterial.prototype, "opacity", void 0);
  91290. __decorate([
  91291. BABYLON.serialize()
  91292. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  91293. return GridMaterial;
  91294. }(BABYLON.PushMaterial));
  91295. BABYLON.GridMaterial = GridMaterial;
  91296. })(BABYLON || (BABYLON = {}));
  91297. //# sourceMappingURL=babylon.gridmaterial.js.map
  91298. 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}";
  91299. 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}";
  91300. "use strict";
  91301. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  91302. var BABYLON;
  91303. (function (BABYLON) {
  91304. var GLTFLoaderCoordinateSystemMode;
  91305. (function (GLTFLoaderCoordinateSystemMode) {
  91306. /**
  91307. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  91308. */
  91309. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  91310. /**
  91311. * Sets the useRightHandedSystem flag on the scene.
  91312. */
  91313. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  91314. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  91315. var GLTFLoaderAnimationStartMode;
  91316. (function (GLTFLoaderAnimationStartMode) {
  91317. /**
  91318. * No animation will start.
  91319. */
  91320. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  91321. /**
  91322. * The first animation will start.
  91323. */
  91324. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  91325. /**
  91326. * All animations will start.
  91327. */
  91328. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  91329. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  91330. var GLTFLoaderState;
  91331. (function (GLTFLoaderState) {
  91332. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  91333. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  91334. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  91335. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  91336. var GLTFFileLoader = /** @class */ (function () {
  91337. function GLTFFileLoader() {
  91338. // #region Common options
  91339. /**
  91340. * Raised when the asset has been parsed.
  91341. * The data.json property stores the glTF JSON.
  91342. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  91343. */
  91344. this.onParsedObservable = new BABYLON.Observable();
  91345. // #endregion
  91346. // #region V2 options
  91347. /**
  91348. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  91349. */
  91350. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  91351. /**
  91352. * The animation start mode (NONE, FIRST, ALL).
  91353. */
  91354. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  91355. /**
  91356. * Set to true to compile materials before raising the success callback.
  91357. */
  91358. this.compileMaterials = false;
  91359. /**
  91360. * Set to true to also compile materials with clip planes.
  91361. */
  91362. this.useClipPlane = false;
  91363. /**
  91364. * Set to true to compile shadow generators before raising the success callback.
  91365. */
  91366. this.compileShadowGenerators = false;
  91367. /**
  91368. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  91369. */
  91370. this.onMeshLoadedObservable = new BABYLON.Observable();
  91371. /**
  91372. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  91373. */
  91374. this.onTextureLoadedObservable = new BABYLON.Observable();
  91375. /**
  91376. * Raised when the loader creates a material after parsing the glTF properties of the material.
  91377. */
  91378. this.onMaterialLoadedObservable = new BABYLON.Observable();
  91379. /**
  91380. * Raised when the loader creates an animation group after parsing the glTF properties of the animation.
  91381. */
  91382. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  91383. /**
  91384. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  91385. * For assets with LODs, raised when all of the LODs are complete.
  91386. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  91387. */
  91388. this.onCompleteObservable = new BABYLON.Observable();
  91389. /**
  91390. * Raised when the loader is disposed.
  91391. */
  91392. this.onDisposeObservable = new BABYLON.Observable();
  91393. /**
  91394. * Raised after a loader extension is created.
  91395. * Set additional options for a loader extension in this event.
  91396. */
  91397. this.onExtensionLoadedObservable = new BABYLON.Observable();
  91398. // #endregion
  91399. this._loader = null;
  91400. this.name = "gltf";
  91401. this.extensions = {
  91402. ".gltf": { isBinary: false },
  91403. ".glb": { isBinary: true }
  91404. };
  91405. }
  91406. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  91407. set: function (callback) {
  91408. if (this._onParsedObserver) {
  91409. this.onParsedObservable.remove(this._onParsedObserver);
  91410. }
  91411. this._onParsedObserver = this.onParsedObservable.add(callback);
  91412. },
  91413. enumerable: true,
  91414. configurable: true
  91415. });
  91416. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  91417. set: function (callback) {
  91418. if (this._onMeshLoadedObserver) {
  91419. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  91420. }
  91421. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  91422. },
  91423. enumerable: true,
  91424. configurable: true
  91425. });
  91426. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  91427. set: function (callback) {
  91428. if (this._onTextureLoadedObserver) {
  91429. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  91430. }
  91431. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  91432. },
  91433. enumerable: true,
  91434. configurable: true
  91435. });
  91436. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  91437. set: function (callback) {
  91438. if (this._onMaterialLoadedObserver) {
  91439. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  91440. }
  91441. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  91442. },
  91443. enumerable: true,
  91444. configurable: true
  91445. });
  91446. Object.defineProperty(GLTFFileLoader.prototype, "onAnimationGroupLoaded", {
  91447. set: function (callback) {
  91448. if (this._onAnimationGroupLoadedObserver) {
  91449. this.onAnimationGroupLoadedObservable.remove(this._onAnimationGroupLoadedObserver);
  91450. }
  91451. this._onAnimationGroupLoadedObserver = this.onAnimationGroupLoadedObservable.add(callback);
  91452. },
  91453. enumerable: true,
  91454. configurable: true
  91455. });
  91456. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  91457. set: function (callback) {
  91458. if (this._onCompleteObserver) {
  91459. this.onCompleteObservable.remove(this._onCompleteObserver);
  91460. }
  91461. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  91462. },
  91463. enumerable: true,
  91464. configurable: true
  91465. });
  91466. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  91467. set: function (callback) {
  91468. if (this._onDisposeObserver) {
  91469. this.onDisposeObservable.remove(this._onDisposeObserver);
  91470. }
  91471. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  91472. },
  91473. enumerable: true,
  91474. configurable: true
  91475. });
  91476. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  91477. set: function (callback) {
  91478. if (this._onExtensionLoadedObserver) {
  91479. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  91480. }
  91481. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  91482. },
  91483. enumerable: true,
  91484. configurable: true
  91485. });
  91486. /**
  91487. * Gets a promise that resolves when the asset is completely loaded.
  91488. * @returns A promise that resolves when the asset is completely loaded.
  91489. */
  91490. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  91491. var _this = this;
  91492. return new Promise(function (resolve) {
  91493. _this.onCompleteObservable.add(function () {
  91494. resolve();
  91495. }, undefined, undefined, undefined, true);
  91496. });
  91497. };
  91498. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  91499. /**
  91500. * The loader state or null if not active.
  91501. */
  91502. get: function () {
  91503. return this._loader ? this._loader.state : null;
  91504. },
  91505. enumerable: true,
  91506. configurable: true
  91507. });
  91508. /**
  91509. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  91510. */
  91511. GLTFFileLoader.prototype.dispose = function () {
  91512. if (this._loader) {
  91513. this._loader.dispose();
  91514. this._loader = null;
  91515. }
  91516. this.onMeshLoadedObservable.clear();
  91517. this.onTextureLoadedObservable.clear();
  91518. this.onMaterialLoadedObservable.clear();
  91519. this.onDisposeObservable.notifyObservers(this);
  91520. this.onDisposeObservable.clear();
  91521. };
  91522. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  91523. var _this = this;
  91524. return Promise.resolve().then(function () {
  91525. var loaderData = _this._parse(data);
  91526. _this._loader = _this._getLoader(loaderData);
  91527. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  91528. });
  91529. };
  91530. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  91531. var _this = this;
  91532. return Promise.resolve().then(function () {
  91533. var loaderData = _this._parse(data);
  91534. _this._loader = _this._getLoader(loaderData);
  91535. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  91536. });
  91537. };
  91538. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  91539. var _this = this;
  91540. return Promise.resolve().then(function () {
  91541. var loaderData = _this._parse(data);
  91542. _this._loader = _this._getLoader(loaderData);
  91543. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  91544. var container = new BABYLON.AssetContainer(scene);
  91545. Array.prototype.push.apply(container.meshes, result.meshes);
  91546. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  91547. Array.prototype.push.apply(container.skeletons, result.skeletons);
  91548. container.removeAllFromScene();
  91549. return container;
  91550. });
  91551. });
  91552. };
  91553. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  91554. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  91555. };
  91556. GLTFFileLoader.prototype.createPlugin = function () {
  91557. return new GLTFFileLoader();
  91558. };
  91559. GLTFFileLoader.prototype._parse = function (data) {
  91560. var parsedData;
  91561. if (data instanceof ArrayBuffer) {
  91562. parsedData = GLTFFileLoader._parseBinary(data);
  91563. }
  91564. else {
  91565. parsedData = {
  91566. json: JSON.parse(data),
  91567. bin: null
  91568. };
  91569. }
  91570. this.onParsedObservable.notifyObservers(parsedData);
  91571. this.onParsedObservable.clear();
  91572. return parsedData;
  91573. };
  91574. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  91575. var _this = this;
  91576. var loaderVersion = { major: 2, minor: 0 };
  91577. var asset = loaderData.json.asset || {};
  91578. var version = GLTFFileLoader._parseVersion(asset.version);
  91579. if (!version) {
  91580. throw new Error("Invalid version: " + asset.version);
  91581. }
  91582. if (asset.minVersion !== undefined) {
  91583. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  91584. if (!minVersion) {
  91585. throw new Error("Invalid minimum version: " + asset.minVersion);
  91586. }
  91587. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  91588. throw new Error("Incompatible minimum version: " + asset.minVersion);
  91589. }
  91590. }
  91591. var createLoaders = {
  91592. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  91593. 2: GLTFFileLoader.CreateGLTFLoaderV2
  91594. };
  91595. var createLoader = createLoaders[version.major];
  91596. if (!createLoader) {
  91597. throw new Error("Unsupported version: " + asset.version);
  91598. }
  91599. var loader = createLoader();
  91600. loader.coordinateSystemMode = this.coordinateSystemMode;
  91601. loader.animationStartMode = this.animationStartMode;
  91602. loader.compileMaterials = this.compileMaterials;
  91603. loader.useClipPlane = this.useClipPlane;
  91604. loader.compileShadowGenerators = this.compileShadowGenerators;
  91605. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  91606. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  91607. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  91608. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  91609. loader.onCompleteObservable.add(function () {
  91610. _this.onMeshLoadedObservable.clear();
  91611. _this.onTextureLoadedObservable.clear();
  91612. _this.onMaterialLoadedObservable.clear();
  91613. _this.onCompleteObservable.notifyObservers(_this);
  91614. _this.onCompleteObservable.clear();
  91615. });
  91616. return loader;
  91617. };
  91618. GLTFFileLoader._parseBinary = function (data) {
  91619. var Binary = {
  91620. Magic: 0x46546C67
  91621. };
  91622. var binaryReader = new BinaryReader(data);
  91623. var magic = binaryReader.readUint32();
  91624. if (magic !== Binary.Magic) {
  91625. throw new Error("Unexpected magic: " + magic);
  91626. }
  91627. var version = binaryReader.readUint32();
  91628. switch (version) {
  91629. case 1: return GLTFFileLoader._parseV1(binaryReader);
  91630. case 2: return GLTFFileLoader._parseV2(binaryReader);
  91631. }
  91632. throw new Error("Unsupported version: " + version);
  91633. };
  91634. GLTFFileLoader._parseV1 = function (binaryReader) {
  91635. var ContentFormat = {
  91636. JSON: 0
  91637. };
  91638. var length = binaryReader.readUint32();
  91639. if (length != binaryReader.getLength()) {
  91640. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  91641. }
  91642. var contentLength = binaryReader.readUint32();
  91643. var contentFormat = binaryReader.readUint32();
  91644. var content;
  91645. switch (contentFormat) {
  91646. case ContentFormat.JSON: {
  91647. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  91648. break;
  91649. }
  91650. default: {
  91651. throw new Error("Unexpected content format: " + contentFormat);
  91652. }
  91653. }
  91654. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  91655. var body = binaryReader.readUint8Array(bytesRemaining);
  91656. return {
  91657. json: content,
  91658. bin: body
  91659. };
  91660. };
  91661. GLTFFileLoader._parseV2 = function (binaryReader) {
  91662. var ChunkFormat = {
  91663. JSON: 0x4E4F534A,
  91664. BIN: 0x004E4942
  91665. };
  91666. var length = binaryReader.readUint32();
  91667. if (length !== binaryReader.getLength()) {
  91668. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  91669. }
  91670. // JSON chunk
  91671. var chunkLength = binaryReader.readUint32();
  91672. var chunkFormat = binaryReader.readUint32();
  91673. if (chunkFormat !== ChunkFormat.JSON) {
  91674. throw new Error("First chunk format is not JSON");
  91675. }
  91676. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  91677. // Look for BIN chunk
  91678. var bin = null;
  91679. while (binaryReader.getPosition() < binaryReader.getLength()) {
  91680. var chunkLength_1 = binaryReader.readUint32();
  91681. var chunkFormat_1 = binaryReader.readUint32();
  91682. switch (chunkFormat_1) {
  91683. case ChunkFormat.JSON: {
  91684. throw new Error("Unexpected JSON chunk");
  91685. }
  91686. case ChunkFormat.BIN: {
  91687. bin = binaryReader.readUint8Array(chunkLength_1);
  91688. break;
  91689. }
  91690. default: {
  91691. // ignore unrecognized chunkFormat
  91692. binaryReader.skipBytes(chunkLength_1);
  91693. break;
  91694. }
  91695. }
  91696. }
  91697. return {
  91698. json: json,
  91699. bin: bin
  91700. };
  91701. };
  91702. GLTFFileLoader._parseVersion = function (version) {
  91703. if (version === "1.0" || version === "1.0.1") {
  91704. return {
  91705. major: 1,
  91706. minor: 0
  91707. };
  91708. }
  91709. var match = (version + "").match(/^(\d+)\.(\d+)/);
  91710. if (!match) {
  91711. return null;
  91712. }
  91713. return {
  91714. major: parseInt(match[1]),
  91715. minor: parseInt(match[2])
  91716. };
  91717. };
  91718. GLTFFileLoader._compareVersion = function (a, b) {
  91719. if (a.major > b.major)
  91720. return 1;
  91721. if (a.major < b.major)
  91722. return -1;
  91723. if (a.minor > b.minor)
  91724. return 1;
  91725. if (a.minor < b.minor)
  91726. return -1;
  91727. return 0;
  91728. };
  91729. GLTFFileLoader._decodeBufferToText = function (buffer) {
  91730. var result = "";
  91731. var length = buffer.byteLength;
  91732. for (var i = 0; i < length; i++) {
  91733. result += String.fromCharCode(buffer[i]);
  91734. }
  91735. return result;
  91736. };
  91737. // #endregion
  91738. // #region V1 options
  91739. GLTFFileLoader.IncrementalLoading = true;
  91740. GLTFFileLoader.HomogeneousCoordinates = false;
  91741. return GLTFFileLoader;
  91742. }());
  91743. BABYLON.GLTFFileLoader = GLTFFileLoader;
  91744. var BinaryReader = /** @class */ (function () {
  91745. function BinaryReader(arrayBuffer) {
  91746. this._arrayBuffer = arrayBuffer;
  91747. this._dataView = new DataView(arrayBuffer);
  91748. this._byteOffset = 0;
  91749. }
  91750. BinaryReader.prototype.getPosition = function () {
  91751. return this._byteOffset;
  91752. };
  91753. BinaryReader.prototype.getLength = function () {
  91754. return this._arrayBuffer.byteLength;
  91755. };
  91756. BinaryReader.prototype.readUint32 = function () {
  91757. var value = this._dataView.getUint32(this._byteOffset, true);
  91758. this._byteOffset += 4;
  91759. return value;
  91760. };
  91761. BinaryReader.prototype.readUint8Array = function (length) {
  91762. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  91763. this._byteOffset += length;
  91764. return value;
  91765. };
  91766. BinaryReader.prototype.skipBytes = function (length) {
  91767. this._byteOffset += length;
  91768. };
  91769. return BinaryReader;
  91770. }());
  91771. if (BABYLON.SceneLoader) {
  91772. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  91773. }
  91774. })(BABYLON || (BABYLON = {}));
  91775. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  91776. "use strict";
  91777. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91778. var BABYLON;
  91779. (function (BABYLON) {
  91780. var GLTF1;
  91781. (function (GLTF1) {
  91782. /**
  91783. * Enums
  91784. */
  91785. var EComponentType;
  91786. (function (EComponentType) {
  91787. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  91788. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  91789. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  91790. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  91791. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  91792. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  91793. var EShaderType;
  91794. (function (EShaderType) {
  91795. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  91796. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  91797. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  91798. var EParameterType;
  91799. (function (EParameterType) {
  91800. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  91801. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  91802. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  91803. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  91804. EParameterType[EParameterType["INT"] = 5124] = "INT";
  91805. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  91806. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  91807. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  91808. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  91809. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  91810. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  91811. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  91812. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  91813. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  91814. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  91815. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  91816. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  91817. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  91818. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  91819. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  91820. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  91821. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  91822. var ETextureWrapMode;
  91823. (function (ETextureWrapMode) {
  91824. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  91825. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  91826. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  91827. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  91828. var ETextureFilterType;
  91829. (function (ETextureFilterType) {
  91830. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  91831. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  91832. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  91833. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  91834. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  91835. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  91836. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  91837. var ETextureFormat;
  91838. (function (ETextureFormat) {
  91839. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  91840. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  91841. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  91842. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  91843. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  91844. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  91845. var ECullingType;
  91846. (function (ECullingType) {
  91847. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  91848. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  91849. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  91850. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  91851. var EBlendingFunction;
  91852. (function (EBlendingFunction) {
  91853. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  91854. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  91855. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  91856. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  91857. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  91858. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  91859. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  91860. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  91861. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  91862. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  91863. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  91864. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  91865. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  91866. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  91867. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  91868. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  91869. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  91870. })(BABYLON || (BABYLON = {}));
  91871. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  91872. "use strict";
  91873. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  91874. var BABYLON;
  91875. (function (BABYLON) {
  91876. var GLTF1;
  91877. (function (GLTF1) {
  91878. /**
  91879. * Tokenizer. Used for shaders compatibility
  91880. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  91881. */
  91882. var ETokenType;
  91883. (function (ETokenType) {
  91884. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  91885. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  91886. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  91887. })(ETokenType || (ETokenType = {}));
  91888. var Tokenizer = /** @class */ (function () {
  91889. function Tokenizer(toParse) {
  91890. this._pos = 0;
  91891. this.currentToken = ETokenType.UNKNOWN;
  91892. this.currentIdentifier = "";
  91893. this.currentString = "";
  91894. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  91895. this._toParse = toParse;
  91896. this._maxPos = toParse.length;
  91897. }
  91898. Tokenizer.prototype.getNextToken = function () {
  91899. if (this.isEnd())
  91900. return ETokenType.END_OF_INPUT;
  91901. this.currentString = this.read();
  91902. this.currentToken = ETokenType.UNKNOWN;
  91903. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  91904. this.currentToken = ETokenType.IDENTIFIER;
  91905. this.currentIdentifier = this.currentString;
  91906. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  91907. this.currentIdentifier += this.currentString;
  91908. this.forward();
  91909. }
  91910. }
  91911. return this.currentToken;
  91912. };
  91913. Tokenizer.prototype.peek = function () {
  91914. return this._toParse[this._pos];
  91915. };
  91916. Tokenizer.prototype.read = function () {
  91917. return this._toParse[this._pos++];
  91918. };
  91919. Tokenizer.prototype.forward = function () {
  91920. this._pos++;
  91921. };
  91922. Tokenizer.prototype.isEnd = function () {
  91923. return this._pos >= this._maxPos;
  91924. };
  91925. return Tokenizer;
  91926. }());
  91927. /**
  91928. * Values
  91929. */
  91930. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  91931. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  91932. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  91933. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  91934. /**
  91935. * Parse
  91936. */
  91937. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  91938. for (var buf in parsedBuffers) {
  91939. var parsedBuffer = parsedBuffers[buf];
  91940. gltfRuntime.buffers[buf] = parsedBuffer;
  91941. gltfRuntime.buffersCount++;
  91942. }
  91943. };
  91944. var parseShaders = function (parsedShaders, gltfRuntime) {
  91945. for (var sha in parsedShaders) {
  91946. var parsedShader = parsedShaders[sha];
  91947. gltfRuntime.shaders[sha] = parsedShader;
  91948. gltfRuntime.shaderscount++;
  91949. }
  91950. };
  91951. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  91952. for (var object in parsedObjects) {
  91953. var parsedObject = parsedObjects[object];
  91954. gltfRuntime[runtimeProperty][object] = parsedObject;
  91955. }
  91956. };
  91957. /**
  91958. * Utils
  91959. */
  91960. var normalizeUVs = function (buffer) {
  91961. if (!buffer) {
  91962. return;
  91963. }
  91964. for (var i = 0; i < buffer.length / 2; i++) {
  91965. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  91966. }
  91967. };
  91968. var getAttribute = function (attributeParameter) {
  91969. if (attributeParameter.semantic === "NORMAL") {
  91970. return "normal";
  91971. }
  91972. else if (attributeParameter.semantic === "POSITION") {
  91973. return "position";
  91974. }
  91975. else if (attributeParameter.semantic === "JOINT") {
  91976. return "matricesIndices";
  91977. }
  91978. else if (attributeParameter.semantic === "WEIGHT") {
  91979. return "matricesWeights";
  91980. }
  91981. else if (attributeParameter.semantic === "COLOR") {
  91982. return "color";
  91983. }
  91984. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  91985. var channel = Number(attributeParameter.semantic.split("_")[1]);
  91986. return "uv" + (channel === 0 ? "" : channel + 1);
  91987. }
  91988. return null;
  91989. };
  91990. /**
  91991. * Loads and creates animations
  91992. */
  91993. var loadAnimations = function (gltfRuntime) {
  91994. for (var anim in gltfRuntime.animations) {
  91995. var animation = gltfRuntime.animations[anim];
  91996. if (!animation.channels || !animation.samplers) {
  91997. continue;
  91998. }
  91999. var lastAnimation = null;
  92000. for (var i = 0; i < animation.channels.length; i++) {
  92001. // Get parameters and load buffers
  92002. var channel = animation.channels[i];
  92003. var sampler = animation.samplers[channel.sampler];
  92004. if (!sampler) {
  92005. continue;
  92006. }
  92007. var inputData = null;
  92008. var outputData = null;
  92009. if (animation.parameters) {
  92010. inputData = animation.parameters[sampler.input];
  92011. outputData = animation.parameters[sampler.output];
  92012. }
  92013. else {
  92014. inputData = sampler.input;
  92015. outputData = sampler.output;
  92016. }
  92017. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  92018. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  92019. var targetID = channel.target.id;
  92020. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  92021. if (targetNode === null) {
  92022. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  92023. }
  92024. if (targetNode === null) {
  92025. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  92026. continue;
  92027. }
  92028. var isBone = targetNode instanceof BABYLON.Bone;
  92029. // Get target path (position, rotation or scaling)
  92030. var targetPath = channel.target.path;
  92031. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  92032. if (targetPathIndex !== -1) {
  92033. targetPath = babylonAnimationPaths[targetPathIndex];
  92034. }
  92035. // Determine animation type
  92036. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  92037. if (!isBone) {
  92038. if (targetPath === "rotationQuaternion") {
  92039. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  92040. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  92041. }
  92042. else {
  92043. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  92044. }
  92045. }
  92046. // Create animation and key frames
  92047. var babylonAnimation = null;
  92048. var keys = [];
  92049. var arrayOffset = 0;
  92050. var modifyKey = false;
  92051. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  92052. babylonAnimation = lastAnimation;
  92053. modifyKey = true;
  92054. }
  92055. if (!modifyKey) {
  92056. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  92057. }
  92058. // For each frame
  92059. for (var j = 0; j < bufferInput.length; j++) {
  92060. var value = null;
  92061. if (targetPath === "rotationQuaternion") {
  92062. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  92063. arrayOffset += 4;
  92064. }
  92065. else {
  92066. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  92067. arrayOffset += 3;
  92068. }
  92069. if (isBone) {
  92070. var bone = targetNode;
  92071. var translation = BABYLON.Vector3.Zero();
  92072. var rotationQuaternion = new BABYLON.Quaternion();
  92073. var scaling = BABYLON.Vector3.Zero();
  92074. // Warning on decompose
  92075. var mat = bone.getBaseMatrix();
  92076. if (modifyKey && lastAnimation) {
  92077. mat = lastAnimation.getKeys()[j].value;
  92078. }
  92079. mat.decompose(scaling, rotationQuaternion, translation);
  92080. if (targetPath === "position") {
  92081. translation = value;
  92082. }
  92083. else if (targetPath === "rotationQuaternion") {
  92084. rotationQuaternion = value;
  92085. }
  92086. else {
  92087. scaling = value;
  92088. }
  92089. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  92090. }
  92091. if (!modifyKey) {
  92092. keys.push({
  92093. frame: bufferInput[j],
  92094. value: value
  92095. });
  92096. }
  92097. else if (lastAnimation) {
  92098. lastAnimation.getKeys()[j].value = value;
  92099. }
  92100. }
  92101. // Finish
  92102. if (!modifyKey && babylonAnimation) {
  92103. babylonAnimation.setKeys(keys);
  92104. targetNode.animations.push(babylonAnimation);
  92105. }
  92106. lastAnimation = babylonAnimation;
  92107. gltfRuntime.scene.stopAnimation(targetNode);
  92108. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  92109. }
  92110. }
  92111. };
  92112. /**
  92113. * Returns the bones transformation matrix
  92114. */
  92115. var configureBoneTransformation = function (node) {
  92116. var mat = null;
  92117. if (node.translation || node.rotation || node.scale) {
  92118. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  92119. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  92120. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  92121. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  92122. }
  92123. else {
  92124. mat = BABYLON.Matrix.FromArray(node.matrix);
  92125. }
  92126. return mat;
  92127. };
  92128. /**
  92129. * Returns the parent bone
  92130. */
  92131. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  92132. // Try to find
  92133. for (var i = 0; i < newSkeleton.bones.length; i++) {
  92134. if (newSkeleton.bones[i].name === jointName) {
  92135. return newSkeleton.bones[i];
  92136. }
  92137. }
  92138. // Not found, search in gltf nodes
  92139. var nodes = gltfRuntime.nodes;
  92140. for (var nde in nodes) {
  92141. var node = nodes[nde];
  92142. if (!node.jointName) {
  92143. continue;
  92144. }
  92145. var children = node.children;
  92146. for (var i = 0; i < children.length; i++) {
  92147. var child = gltfRuntime.nodes[children[i]];
  92148. if (!child.jointName) {
  92149. continue;
  92150. }
  92151. if (child.jointName === jointName) {
  92152. var mat = configureBoneTransformation(node);
  92153. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  92154. bone.id = nde;
  92155. return bone;
  92156. }
  92157. }
  92158. }
  92159. return null;
  92160. };
  92161. /**
  92162. * Returns the appropriate root node
  92163. */
  92164. var getNodeToRoot = function (nodesToRoot, id) {
  92165. for (var i = 0; i < nodesToRoot.length; i++) {
  92166. var nodeToRoot = nodesToRoot[i];
  92167. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  92168. var child = nodeToRoot.node.children[j];
  92169. if (child === id) {
  92170. return nodeToRoot.bone;
  92171. }
  92172. }
  92173. }
  92174. return null;
  92175. };
  92176. /**
  92177. * Returns the node with the joint name
  92178. */
  92179. var getJointNode = function (gltfRuntime, jointName) {
  92180. var nodes = gltfRuntime.nodes;
  92181. var node = nodes[jointName];
  92182. if (node) {
  92183. return {
  92184. node: node,
  92185. id: jointName
  92186. };
  92187. }
  92188. for (var nde in nodes) {
  92189. node = nodes[nde];
  92190. if (node.jointName === jointName) {
  92191. return {
  92192. node: node,
  92193. id: nde
  92194. };
  92195. }
  92196. }
  92197. return null;
  92198. };
  92199. /**
  92200. * Checks if a nodes is in joints
  92201. */
  92202. var nodeIsInJoints = function (skins, id) {
  92203. for (var i = 0; i < skins.jointNames.length; i++) {
  92204. if (skins.jointNames[i] === id) {
  92205. return true;
  92206. }
  92207. }
  92208. return false;
  92209. };
  92210. /**
  92211. * Fills the nodes to root for bones and builds hierarchy
  92212. */
  92213. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  92214. // Creates nodes for root
  92215. for (var nde in gltfRuntime.nodes) {
  92216. var node = gltfRuntime.nodes[nde];
  92217. var id = nde;
  92218. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  92219. continue;
  92220. }
  92221. // Create node to root bone
  92222. var mat = configureBoneTransformation(node);
  92223. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  92224. bone.id = id;
  92225. nodesToRoot.push({ bone: bone, node: node, id: id });
  92226. }
  92227. // Parenting
  92228. for (var i = 0; i < nodesToRoot.length; i++) {
  92229. var nodeToRoot = nodesToRoot[i];
  92230. var children = nodeToRoot.node.children;
  92231. for (var j = 0; j < children.length; j++) {
  92232. var child = null;
  92233. for (var k = 0; k < nodesToRoot.length; k++) {
  92234. if (nodesToRoot[k].id === children[j]) {
  92235. child = nodesToRoot[k];
  92236. break;
  92237. }
  92238. }
  92239. if (child) {
  92240. child.bone._parent = nodeToRoot.bone;
  92241. nodeToRoot.bone.children.push(child.bone);
  92242. }
  92243. }
  92244. }
  92245. };
  92246. /**
  92247. * Imports a skeleton
  92248. */
  92249. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  92250. if (!newSkeleton) {
  92251. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  92252. }
  92253. if (!skins.babylonSkeleton) {
  92254. return newSkeleton;
  92255. }
  92256. // Find the root bones
  92257. var nodesToRoot = [];
  92258. var nodesToRootToAdd = [];
  92259. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  92260. newSkeleton.bones = [];
  92261. // Joints
  92262. for (var i = 0; i < skins.jointNames.length; i++) {
  92263. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  92264. if (!jointNode) {
  92265. continue;
  92266. }
  92267. var node = jointNode.node;
  92268. if (!node) {
  92269. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  92270. continue;
  92271. }
  92272. var id = jointNode.id;
  92273. // Optimize, if the bone already exists...
  92274. var existingBone = gltfRuntime.scene.getBoneByID(id);
  92275. if (existingBone) {
  92276. newSkeleton.bones.push(existingBone);
  92277. continue;
  92278. }
  92279. // Search for parent bone
  92280. var foundBone = false;
  92281. var parentBone = null;
  92282. for (var j = 0; j < i; j++) {
  92283. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  92284. if (!jointNode_1) {
  92285. continue;
  92286. }
  92287. var joint = jointNode_1.node;
  92288. if (!joint) {
  92289. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  92290. continue;
  92291. }
  92292. var children = joint.children;
  92293. if (!children) {
  92294. continue;
  92295. }
  92296. foundBone = false;
  92297. for (var k = 0; k < children.length; k++) {
  92298. if (children[k] === id) {
  92299. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  92300. foundBone = true;
  92301. break;
  92302. }
  92303. }
  92304. if (foundBone) {
  92305. break;
  92306. }
  92307. }
  92308. // Create bone
  92309. var mat = configureBoneTransformation(node);
  92310. if (!parentBone && nodesToRoot.length > 0) {
  92311. parentBone = getNodeToRoot(nodesToRoot, id);
  92312. if (parentBone) {
  92313. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  92314. nodesToRootToAdd.push(parentBone);
  92315. }
  92316. }
  92317. }
  92318. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  92319. bone.id = id;
  92320. }
  92321. // Polish
  92322. var bones = newSkeleton.bones;
  92323. newSkeleton.bones = [];
  92324. for (var i = 0; i < skins.jointNames.length; i++) {
  92325. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  92326. if (!jointNode) {
  92327. continue;
  92328. }
  92329. for (var j = 0; j < bones.length; j++) {
  92330. if (bones[j].id === jointNode.id) {
  92331. newSkeleton.bones.push(bones[j]);
  92332. break;
  92333. }
  92334. }
  92335. }
  92336. newSkeleton.prepare();
  92337. // Finish
  92338. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  92339. newSkeleton.bones.push(nodesToRootToAdd[i]);
  92340. }
  92341. return newSkeleton;
  92342. };
  92343. /**
  92344. * Imports a mesh and its geometries
  92345. */
  92346. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  92347. if (!newMesh) {
  92348. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  92349. newMesh.id = id;
  92350. }
  92351. if (!node.babylonNode) {
  92352. return newMesh;
  92353. }
  92354. var subMaterials = [];
  92355. var vertexData = null;
  92356. var verticesStarts = new Array();
  92357. var verticesCounts = new Array();
  92358. var indexStarts = new Array();
  92359. var indexCounts = new Array();
  92360. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  92361. var meshID = meshes[meshIndex];
  92362. var mesh = gltfRuntime.meshes[meshID];
  92363. if (!mesh) {
  92364. continue;
  92365. }
  92366. // Positions, normals and UVs
  92367. for (var i = 0; i < mesh.primitives.length; i++) {
  92368. // Temporary vertex data
  92369. var tempVertexData = new BABYLON.VertexData();
  92370. var primitive = mesh.primitives[i];
  92371. if (primitive.mode !== 4) {
  92372. // continue;
  92373. }
  92374. var attributes = primitive.attributes;
  92375. var accessor = null;
  92376. var buffer = null;
  92377. // Set positions, normal and uvs
  92378. for (var semantic in attributes) {
  92379. // Link accessor and buffer view
  92380. accessor = gltfRuntime.accessors[attributes[semantic]];
  92381. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  92382. if (semantic === "NORMAL") {
  92383. tempVertexData.normals = new Float32Array(buffer.length);
  92384. tempVertexData.normals.set(buffer);
  92385. }
  92386. else if (semantic === "POSITION") {
  92387. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  92388. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  92389. for (var j = 0; j < buffer.length; j += 4) {
  92390. tempVertexData.positions[j] = buffer[j];
  92391. tempVertexData.positions[j + 1] = buffer[j + 1];
  92392. tempVertexData.positions[j + 2] = buffer[j + 2];
  92393. }
  92394. }
  92395. else {
  92396. tempVertexData.positions = new Float32Array(buffer.length);
  92397. tempVertexData.positions.set(buffer);
  92398. }
  92399. verticesCounts.push(tempVertexData.positions.length);
  92400. }
  92401. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  92402. var channel = Number(semantic.split("_")[1]);
  92403. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  92404. var uvs = new Float32Array(buffer.length);
  92405. uvs.set(buffer);
  92406. normalizeUVs(uvs);
  92407. tempVertexData.set(uvs, uvKind);
  92408. }
  92409. else if (semantic === "JOINT") {
  92410. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  92411. tempVertexData.matricesIndices.set(buffer);
  92412. }
  92413. else if (semantic === "WEIGHT") {
  92414. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  92415. tempVertexData.matricesWeights.set(buffer);
  92416. }
  92417. else if (semantic === "COLOR") {
  92418. tempVertexData.colors = new Float32Array(buffer.length);
  92419. tempVertexData.colors.set(buffer);
  92420. }
  92421. }
  92422. // Indices
  92423. accessor = gltfRuntime.accessors[primitive.indices];
  92424. if (accessor) {
  92425. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  92426. tempVertexData.indices = new Int32Array(buffer.length);
  92427. tempVertexData.indices.set(buffer);
  92428. indexCounts.push(tempVertexData.indices.length);
  92429. }
  92430. else {
  92431. // Set indices on the fly
  92432. var indices = [];
  92433. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  92434. indices.push(j);
  92435. }
  92436. tempVertexData.indices = new Int32Array(indices);
  92437. indexCounts.push(tempVertexData.indices.length);
  92438. }
  92439. if (!vertexData) {
  92440. vertexData = tempVertexData;
  92441. }
  92442. else {
  92443. vertexData.merge(tempVertexData);
  92444. }
  92445. // Sub material
  92446. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  92447. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  92448. // Update vertices start and index start
  92449. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  92450. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  92451. }
  92452. }
  92453. var material;
  92454. if (subMaterials.length > 1) {
  92455. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  92456. material.subMaterials = subMaterials;
  92457. }
  92458. else {
  92459. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  92460. }
  92461. if (subMaterials.length === 1) {
  92462. material = subMaterials[0];
  92463. }
  92464. if (!newMesh.material) {
  92465. newMesh.material = material;
  92466. }
  92467. // Apply geometry
  92468. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  92469. newMesh.computeWorldMatrix(true);
  92470. // Apply submeshes
  92471. newMesh.subMeshes = [];
  92472. var index = 0;
  92473. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  92474. var meshID = meshes[meshIndex];
  92475. var mesh = gltfRuntime.meshes[meshID];
  92476. if (!mesh) {
  92477. continue;
  92478. }
  92479. for (var i = 0; i < mesh.primitives.length; i++) {
  92480. if (mesh.primitives[i].mode !== 4) {
  92481. //continue;
  92482. }
  92483. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  92484. index++;
  92485. }
  92486. }
  92487. // Finish
  92488. return newMesh;
  92489. };
  92490. /**
  92491. * Configure node transformation from position, rotation and scaling
  92492. */
  92493. var configureNode = function (newNode, position, rotation, scaling) {
  92494. if (newNode.position) {
  92495. newNode.position = position;
  92496. }
  92497. if (newNode.rotationQuaternion || newNode.rotation) {
  92498. newNode.rotationQuaternion = rotation;
  92499. }
  92500. if (newNode.scaling) {
  92501. newNode.scaling = scaling;
  92502. }
  92503. };
  92504. /**
  92505. * Configures node from transformation matrix
  92506. */
  92507. var configureNodeFromMatrix = function (newNode, node, parent) {
  92508. if (node.matrix) {
  92509. var position = new BABYLON.Vector3(0, 0, 0);
  92510. var rotation = new BABYLON.Quaternion();
  92511. var scaling = new BABYLON.Vector3(0, 0, 0);
  92512. var mat = BABYLON.Matrix.FromArray(node.matrix);
  92513. mat.decompose(scaling, rotation, position);
  92514. configureNode(newNode, position, rotation, scaling);
  92515. }
  92516. else if (node.translation && node.rotation && node.scale) {
  92517. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  92518. }
  92519. newNode.computeWorldMatrix(true);
  92520. };
  92521. /**
  92522. * Imports a node
  92523. */
  92524. var importNode = function (gltfRuntime, node, id, parent) {
  92525. var lastNode = null;
  92526. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  92527. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  92528. return null;
  92529. }
  92530. }
  92531. // Meshes
  92532. if (node.skin) {
  92533. if (node.meshes) {
  92534. var skin = gltfRuntime.skins[node.skin];
  92535. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  92536. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  92537. if (newMesh.skeleton === null) {
  92538. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  92539. if (!skin.babylonSkeleton) {
  92540. skin.babylonSkeleton = newMesh.skeleton;
  92541. }
  92542. }
  92543. lastNode = newMesh;
  92544. }
  92545. }
  92546. else if (node.meshes) {
  92547. /**
  92548. * Improve meshes property
  92549. */
  92550. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  92551. lastNode = newMesh;
  92552. }
  92553. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  92554. var light = gltfRuntime.lights[node.light];
  92555. if (light) {
  92556. if (light.type === "ambient") {
  92557. var ambienLight = light[light.type];
  92558. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92559. hemiLight.name = node.name || "";
  92560. if (ambienLight.color) {
  92561. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  92562. }
  92563. lastNode = hemiLight;
  92564. }
  92565. else if (light.type === "directional") {
  92566. var directionalLight = light[light.type];
  92567. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92568. dirLight.name = node.name || "";
  92569. if (directionalLight.color) {
  92570. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  92571. }
  92572. lastNode = dirLight;
  92573. }
  92574. else if (light.type === "point") {
  92575. var pointLight = light[light.type];
  92576. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92577. ptLight.name = node.name || "";
  92578. if (pointLight.color) {
  92579. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  92580. }
  92581. lastNode = ptLight;
  92582. }
  92583. else if (light.type === "spot") {
  92584. var spotLight = light[light.type];
  92585. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  92586. spLight.name = node.name || "";
  92587. if (spotLight.color) {
  92588. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  92589. }
  92590. if (spotLight.fallOfAngle) {
  92591. spLight.angle = spotLight.fallOfAngle;
  92592. }
  92593. if (spotLight.fallOffExponent) {
  92594. spLight.exponent = spotLight.fallOffExponent;
  92595. }
  92596. lastNode = spLight;
  92597. }
  92598. }
  92599. }
  92600. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  92601. var camera = gltfRuntime.cameras[node.camera];
  92602. if (camera) {
  92603. if (camera.type === "orthographic") {
  92604. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92605. orthoCamera.name = node.name || "";
  92606. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  92607. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  92608. lastNode = orthoCamera;
  92609. }
  92610. else if (camera.type === "perspective") {
  92611. var perspectiveCamera = camera[camera.type];
  92612. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  92613. persCamera.name = node.name || "";
  92614. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  92615. if (!perspectiveCamera.aspectRatio) {
  92616. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  92617. }
  92618. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  92619. persCamera.maxZ = perspectiveCamera.zfar;
  92620. persCamera.minZ = perspectiveCamera.znear;
  92621. }
  92622. lastNode = persCamera;
  92623. }
  92624. }
  92625. }
  92626. // Empty node
  92627. if (!node.jointName) {
  92628. if (node.babylonNode) {
  92629. return node.babylonNode;
  92630. }
  92631. else if (lastNode === null) {
  92632. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  92633. node.babylonNode = dummy;
  92634. lastNode = dummy;
  92635. }
  92636. }
  92637. if (lastNode !== null) {
  92638. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  92639. configureNodeFromMatrix(lastNode, node, parent);
  92640. }
  92641. else {
  92642. var translation = node.translation || [0, 0, 0];
  92643. var rotation = node.rotation || [0, 0, 0, 1];
  92644. var scale = node.scale || [1, 1, 1];
  92645. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  92646. }
  92647. lastNode.updateCache(true);
  92648. node.babylonNode = lastNode;
  92649. }
  92650. return lastNode;
  92651. };
  92652. /**
  92653. * Traverses nodes and creates them
  92654. */
  92655. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  92656. if (meshIncluded === void 0) { meshIncluded = false; }
  92657. var node = gltfRuntime.nodes[id];
  92658. var newNode = null;
  92659. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  92660. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  92661. meshIncluded = true;
  92662. }
  92663. else {
  92664. meshIncluded = false;
  92665. }
  92666. }
  92667. else {
  92668. meshIncluded = true;
  92669. }
  92670. if (!node.jointName && meshIncluded) {
  92671. newNode = importNode(gltfRuntime, node, id, parent);
  92672. if (newNode !== null) {
  92673. newNode.id = id;
  92674. newNode.parent = parent;
  92675. }
  92676. }
  92677. if (node.children) {
  92678. for (var i = 0; i < node.children.length; i++) {
  92679. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  92680. }
  92681. }
  92682. };
  92683. /**
  92684. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  92685. */
  92686. var postLoad = function (gltfRuntime) {
  92687. // Nodes
  92688. var currentScene = gltfRuntime.currentScene;
  92689. if (currentScene) {
  92690. for (var i = 0; i < currentScene.nodes.length; i++) {
  92691. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92692. }
  92693. }
  92694. else {
  92695. for (var thing in gltfRuntime.scenes) {
  92696. currentScene = gltfRuntime.scenes[thing];
  92697. for (var i = 0; i < currentScene.nodes.length; i++) {
  92698. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  92699. }
  92700. }
  92701. }
  92702. // Set animations
  92703. loadAnimations(gltfRuntime);
  92704. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  92705. var skeleton = gltfRuntime.scene.skeletons[i];
  92706. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  92707. }
  92708. };
  92709. /**
  92710. * onBind shaderrs callback to set uniforms and matrices
  92711. */
  92712. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  92713. var materialValues = material.values || technique.parameters;
  92714. for (var unif in unTreatedUniforms) {
  92715. var uniform = unTreatedUniforms[unif];
  92716. var type = uniform.type;
  92717. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  92718. if (uniform.semantic && !uniform.source && !uniform.node) {
  92719. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  92720. }
  92721. else if (uniform.semantic && (uniform.source || uniform.node)) {
  92722. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  92723. if (source === null) {
  92724. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  92725. }
  92726. if (source === null) {
  92727. continue;
  92728. }
  92729. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  92730. }
  92731. }
  92732. else {
  92733. var value = materialValues[technique.uniforms[unif]];
  92734. if (!value) {
  92735. continue;
  92736. }
  92737. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  92738. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  92739. if (texture === null || texture === undefined) {
  92740. continue;
  92741. }
  92742. shaderMaterial.getEffect().setTexture(unif, texture);
  92743. }
  92744. else {
  92745. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  92746. }
  92747. }
  92748. }
  92749. onSuccess(shaderMaterial);
  92750. };
  92751. /**
  92752. * Prepare uniforms to send the only one time
  92753. * Loads the appropriate textures
  92754. */
  92755. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  92756. var materialValues = material.values || technique.parameters;
  92757. var techniqueUniforms = technique.uniforms;
  92758. /**
  92759. * Prepare values here (not matrices)
  92760. */
  92761. for (var unif in unTreatedUniforms) {
  92762. var uniform = unTreatedUniforms[unif];
  92763. var type = uniform.type;
  92764. var value = materialValues[techniqueUniforms[unif]];
  92765. if (value === undefined) {
  92766. // In case the value is the same for all materials
  92767. value = uniform.value;
  92768. }
  92769. if (!value) {
  92770. continue;
  92771. }
  92772. var onLoadTexture = function (uniformName) {
  92773. return function (texture) {
  92774. if (uniform.value && uniformName) {
  92775. // Static uniform
  92776. shaderMaterial.setTexture(uniformName, texture);
  92777. delete unTreatedUniforms[uniformName];
  92778. }
  92779. };
  92780. };
  92781. // Texture (sampler2D)
  92782. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  92783. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  92784. }
  92785. else {
  92786. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  92787. // Static uniform
  92788. delete unTreatedUniforms[unif];
  92789. }
  92790. }
  92791. }
  92792. };
  92793. /**
  92794. * Shader compilation failed
  92795. */
  92796. var onShaderCompileError = function (program, shaderMaterial, onError) {
  92797. return function (effect, error) {
  92798. shaderMaterial.dispose(true);
  92799. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  92800. };
  92801. };
  92802. /**
  92803. * Shader compilation success
  92804. */
  92805. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  92806. return function (_) {
  92807. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  92808. shaderMaterial.onBind = function (mesh) {
  92809. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  92810. };
  92811. };
  92812. };
  92813. /**
  92814. * Returns the appropriate uniform if already handled by babylon
  92815. */
  92816. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  92817. for (var unif in technique.uniforms) {
  92818. var uniform = technique.uniforms[unif];
  92819. var uniformParameter = technique.parameters[uniform];
  92820. if (tokenizer.currentIdentifier === unif) {
  92821. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  92822. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  92823. if (transformIndex !== -1) {
  92824. delete unTreatedUniforms[unif];
  92825. return babylonTransforms[transformIndex];
  92826. }
  92827. }
  92828. }
  92829. }
  92830. return tokenizer.currentIdentifier;
  92831. };
  92832. /**
  92833. * All shaders loaded. Create materials one by one
  92834. */
  92835. var importMaterials = function (gltfRuntime) {
  92836. // Create materials
  92837. for (var mat in gltfRuntime.materials) {
  92838. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  92839. }
  92840. };
  92841. /**
  92842. * Implementation of the base glTF spec
  92843. */
  92844. var GLTFLoaderBase = /** @class */ (function () {
  92845. function GLTFLoaderBase() {
  92846. }
  92847. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  92848. var gltfRuntime = {
  92849. extensions: {},
  92850. accessors: {},
  92851. buffers: {},
  92852. bufferViews: {},
  92853. meshes: {},
  92854. lights: {},
  92855. cameras: {},
  92856. nodes: {},
  92857. images: {},
  92858. textures: {},
  92859. shaders: {},
  92860. programs: {},
  92861. samplers: {},
  92862. techniques: {},
  92863. materials: {},
  92864. animations: {},
  92865. skins: {},
  92866. extensionsUsed: [],
  92867. scenes: {},
  92868. buffersCount: 0,
  92869. shaderscount: 0,
  92870. scene: scene,
  92871. rootUrl: rootUrl,
  92872. loadedBufferCount: 0,
  92873. loadedBufferViews: {},
  92874. loadedShaderCount: 0,
  92875. importOnlyMeshes: false,
  92876. dummyNodes: []
  92877. };
  92878. // Parse
  92879. if (parsedData.extensions) {
  92880. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  92881. }
  92882. if (parsedData.extensionsUsed) {
  92883. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  92884. }
  92885. if (parsedData.buffers) {
  92886. parseBuffers(parsedData.buffers, gltfRuntime);
  92887. }
  92888. if (parsedData.bufferViews) {
  92889. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  92890. }
  92891. if (parsedData.accessors) {
  92892. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  92893. }
  92894. if (parsedData.meshes) {
  92895. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  92896. }
  92897. if (parsedData.lights) {
  92898. parseObject(parsedData.lights, "lights", gltfRuntime);
  92899. }
  92900. if (parsedData.cameras) {
  92901. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  92902. }
  92903. if (parsedData.nodes) {
  92904. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  92905. }
  92906. if (parsedData.images) {
  92907. parseObject(parsedData.images, "images", gltfRuntime);
  92908. }
  92909. if (parsedData.textures) {
  92910. parseObject(parsedData.textures, "textures", gltfRuntime);
  92911. }
  92912. if (parsedData.shaders) {
  92913. parseShaders(parsedData.shaders, gltfRuntime);
  92914. }
  92915. if (parsedData.programs) {
  92916. parseObject(parsedData.programs, "programs", gltfRuntime);
  92917. }
  92918. if (parsedData.samplers) {
  92919. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  92920. }
  92921. if (parsedData.techniques) {
  92922. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  92923. }
  92924. if (parsedData.materials) {
  92925. parseObject(parsedData.materials, "materials", gltfRuntime);
  92926. }
  92927. if (parsedData.animations) {
  92928. parseObject(parsedData.animations, "animations", gltfRuntime);
  92929. }
  92930. if (parsedData.skins) {
  92931. parseObject(parsedData.skins, "skins", gltfRuntime);
  92932. }
  92933. if (parsedData.scenes) {
  92934. gltfRuntime.scenes = parsedData.scenes;
  92935. }
  92936. if (parsedData.scene && parsedData.scenes) {
  92937. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  92938. }
  92939. return gltfRuntime;
  92940. };
  92941. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  92942. var buffer = gltfRuntime.buffers[id];
  92943. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  92944. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  92945. }
  92946. else {
  92947. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  92948. if (request) {
  92949. onError(request.status + " " + request.statusText);
  92950. }
  92951. });
  92952. }
  92953. };
  92954. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  92955. var texture = gltfRuntime.textures[id];
  92956. if (!texture || !texture.source) {
  92957. onError("");
  92958. return;
  92959. }
  92960. if (texture.babylonTexture) {
  92961. onSuccess(null);
  92962. return;
  92963. }
  92964. var source = gltfRuntime.images[texture.source];
  92965. if (BABYLON.Tools.IsBase64(source.uri)) {
  92966. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  92967. }
  92968. else {
  92969. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  92970. if (request) {
  92971. onError(request.status + " " + request.statusText);
  92972. }
  92973. });
  92974. }
  92975. };
  92976. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  92977. var texture = gltfRuntime.textures[id];
  92978. if (texture.babylonTexture) {
  92979. onSuccess(texture.babylonTexture);
  92980. return;
  92981. }
  92982. var sampler = gltfRuntime.samplers[texture.sampler];
  92983. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  92984. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  92985. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  92986. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  92987. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  92988. var blob = new Blob([buffer]);
  92989. var blobURL = URL.createObjectURL(blob);
  92990. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  92991. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  92992. if (sampler.wrapS !== undefined) {
  92993. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  92994. }
  92995. if (sampler.wrapT !== undefined) {
  92996. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  92997. }
  92998. newTexture.name = id;
  92999. texture.babylonTexture = newTexture;
  93000. onSuccess(newTexture);
  93001. };
  93002. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  93003. var shader = gltfRuntime.shaders[id];
  93004. if (BABYLON.Tools.IsBase64(shader.uri)) {
  93005. var shaderString = atob(shader.uri.split(",")[1]);
  93006. if (onSuccess) {
  93007. onSuccess(shaderString);
  93008. }
  93009. }
  93010. else {
  93011. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  93012. if (request && onError) {
  93013. onError(request.status + " " + request.statusText);
  93014. }
  93015. });
  93016. }
  93017. };
  93018. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  93019. var material = gltfRuntime.materials[id];
  93020. if (!material.technique) {
  93021. if (onError) {
  93022. onError("No technique found.");
  93023. }
  93024. return;
  93025. }
  93026. var technique = gltfRuntime.techniques[material.technique];
  93027. if (!technique) {
  93028. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  93029. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  93030. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  93031. onSuccess(defaultMaterial);
  93032. return;
  93033. }
  93034. var program = gltfRuntime.programs[technique.program];
  93035. var states = technique.states;
  93036. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  93037. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  93038. var newVertexShader = "";
  93039. var newPixelShader = "";
  93040. var vertexTokenizer = new Tokenizer(vertexShader);
  93041. var pixelTokenizer = new Tokenizer(pixelShader);
  93042. var unTreatedUniforms = {};
  93043. var uniforms = [];
  93044. var attributes = [];
  93045. var samplers = [];
  93046. // Fill uniform, sampler2D and attributes
  93047. for (var unif in technique.uniforms) {
  93048. var uniform = technique.uniforms[unif];
  93049. var uniformParameter = technique.parameters[uniform];
  93050. unTreatedUniforms[unif] = uniformParameter;
  93051. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  93052. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  93053. if (transformIndex !== -1) {
  93054. uniforms.push(babylonTransforms[transformIndex]);
  93055. delete unTreatedUniforms[unif];
  93056. }
  93057. else {
  93058. uniforms.push(unif);
  93059. }
  93060. }
  93061. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  93062. samplers.push(unif);
  93063. }
  93064. else {
  93065. uniforms.push(unif);
  93066. }
  93067. }
  93068. for (var attr in technique.attributes) {
  93069. var attribute = technique.attributes[attr];
  93070. var attributeParameter = technique.parameters[attribute];
  93071. if (attributeParameter.semantic) {
  93072. attributes.push(getAttribute(attributeParameter));
  93073. }
  93074. }
  93075. // Configure vertex shader
  93076. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  93077. var tokenType = vertexTokenizer.currentToken;
  93078. if (tokenType !== ETokenType.IDENTIFIER) {
  93079. newVertexShader += vertexTokenizer.currentString;
  93080. continue;
  93081. }
  93082. var foundAttribute = false;
  93083. for (var attr in technique.attributes) {
  93084. var attribute = technique.attributes[attr];
  93085. var attributeParameter = technique.parameters[attribute];
  93086. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  93087. newVertexShader += getAttribute(attributeParameter);
  93088. foundAttribute = true;
  93089. break;
  93090. }
  93091. }
  93092. if (foundAttribute) {
  93093. continue;
  93094. }
  93095. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  93096. }
  93097. // Configure pixel shader
  93098. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  93099. var tokenType = pixelTokenizer.currentToken;
  93100. if (tokenType !== ETokenType.IDENTIFIER) {
  93101. newPixelShader += pixelTokenizer.currentString;
  93102. continue;
  93103. }
  93104. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  93105. }
  93106. // Create shader material
  93107. var shaderPath = {
  93108. vertex: program.vertexShader + id,
  93109. fragment: program.fragmentShader + id
  93110. };
  93111. var options = {
  93112. attributes: attributes,
  93113. uniforms: uniforms,
  93114. samplers: samplers,
  93115. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  93116. };
  93117. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  93118. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  93119. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  93120. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  93121. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  93122. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  93123. if (states && states.functions) {
  93124. var functions = states.functions;
  93125. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  93126. shaderMaterial.backFaceCulling = false;
  93127. }
  93128. var blendFunc = functions.blendFuncSeparate;
  93129. if (blendFunc) {
  93130. 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) {
  93131. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  93132. }
  93133. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  93134. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  93135. }
  93136. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  93137. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  93138. }
  93139. 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) {
  93140. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  93141. }
  93142. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  93143. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  93144. }
  93145. 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) {
  93146. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  93147. }
  93148. }
  93149. }
  93150. };
  93151. return GLTFLoaderBase;
  93152. }());
  93153. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  93154. /**
  93155. * glTF V1 Loader
  93156. */
  93157. var GLTFLoader = /** @class */ (function () {
  93158. function GLTFLoader() {
  93159. // #region Stubs for IGLTFLoader interface
  93160. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  93161. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  93162. this.compileMaterials = false;
  93163. this.useClipPlane = false;
  93164. this.compileShadowGenerators = false;
  93165. this.onDisposeObservable = new BABYLON.Observable();
  93166. this.onMeshLoadedObservable = new BABYLON.Observable();
  93167. this.onTextureLoadedObservable = new BABYLON.Observable();
  93168. this.onMaterialLoadedObservable = new BABYLON.Observable();
  93169. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  93170. this.onCompleteObservable = new BABYLON.Observable();
  93171. this.onExtensionLoadedObservable = new BABYLON.Observable();
  93172. this.state = null;
  93173. }
  93174. GLTFLoader.RegisterExtension = function (extension) {
  93175. if (GLTFLoader.Extensions[extension.name]) {
  93176. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  93177. return;
  93178. }
  93179. GLTFLoader.Extensions[extension.name] = extension;
  93180. };
  93181. GLTFLoader.prototype.dispose = function () { };
  93182. // #endregion
  93183. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  93184. var _this = this;
  93185. scene.useRightHandedSystem = true;
  93186. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  93187. gltfRuntime.importOnlyMeshes = true;
  93188. if (meshesNames === "") {
  93189. gltfRuntime.importMeshesNames = [];
  93190. }
  93191. else if (typeof meshesNames === "string") {
  93192. gltfRuntime.importMeshesNames = [meshesNames];
  93193. }
  93194. else if (meshesNames && !(meshesNames instanceof Array)) {
  93195. gltfRuntime.importMeshesNames = [meshesNames];
  93196. }
  93197. else {
  93198. gltfRuntime.importMeshesNames = [];
  93199. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  93200. }
  93201. // Create nodes
  93202. _this._createNodes(gltfRuntime);
  93203. var meshes = new Array();
  93204. var skeletons = new Array();
  93205. // Fill arrays of meshes and skeletons
  93206. for (var nde in gltfRuntime.nodes) {
  93207. var node = gltfRuntime.nodes[nde];
  93208. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  93209. meshes.push(node.babylonNode);
  93210. }
  93211. }
  93212. for (var skl in gltfRuntime.skins) {
  93213. var skin = gltfRuntime.skins[skl];
  93214. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  93215. skeletons.push(skin.babylonSkeleton);
  93216. }
  93217. }
  93218. // Load buffers, shaders, materials, etc.
  93219. _this._loadBuffersAsync(gltfRuntime, function () {
  93220. _this._loadShadersAsync(gltfRuntime, function () {
  93221. importMaterials(gltfRuntime);
  93222. postLoad(gltfRuntime);
  93223. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  93224. onSuccess(meshes, [], skeletons);
  93225. }
  93226. });
  93227. }, onProgress);
  93228. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  93229. onSuccess(meshes, [], skeletons);
  93230. }
  93231. }, onError);
  93232. return true;
  93233. };
  93234. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  93235. var _this = this;
  93236. return new Promise(function (resolve, reject) {
  93237. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  93238. resolve({
  93239. meshes: meshes,
  93240. particleSystems: particleSystems,
  93241. skeletons: skeletons
  93242. });
  93243. }, onProgress, function (message) {
  93244. reject(new Error(message));
  93245. });
  93246. });
  93247. };
  93248. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  93249. var _this = this;
  93250. scene.useRightHandedSystem = true;
  93251. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  93252. // Load runtime extensios
  93253. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  93254. // Create nodes
  93255. _this._createNodes(gltfRuntime);
  93256. // Load buffers, shaders, materials, etc.
  93257. _this._loadBuffersAsync(gltfRuntime, function () {
  93258. _this._loadShadersAsync(gltfRuntime, function () {
  93259. importMaterials(gltfRuntime);
  93260. postLoad(gltfRuntime);
  93261. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  93262. onSuccess();
  93263. }
  93264. });
  93265. });
  93266. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  93267. onSuccess();
  93268. }
  93269. }, onError);
  93270. }, onError);
  93271. };
  93272. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  93273. var _this = this;
  93274. return new Promise(function (resolve, reject) {
  93275. _this._loadAsync(scene, data, rootUrl, function () {
  93276. resolve();
  93277. }, onProgress, function (message) {
  93278. reject(new Error(message));
  93279. });
  93280. });
  93281. };
  93282. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  93283. var hasShaders = false;
  93284. var processShader = function (sha, shader) {
  93285. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  93286. if (shaderString instanceof ArrayBuffer) {
  93287. return;
  93288. }
  93289. gltfRuntime.loadedShaderCount++;
  93290. if (shaderString) {
  93291. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  93292. }
  93293. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  93294. onload();
  93295. }
  93296. }, function () {
  93297. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  93298. });
  93299. };
  93300. for (var sha in gltfRuntime.shaders) {
  93301. hasShaders = true;
  93302. var shader = gltfRuntime.shaders[sha];
  93303. if (shader) {
  93304. processShader.bind(this, sha, shader)();
  93305. }
  93306. else {
  93307. BABYLON.Tools.Error("No shader named: " + sha);
  93308. }
  93309. }
  93310. if (!hasShaders) {
  93311. onload();
  93312. }
  93313. };
  93314. ;
  93315. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  93316. var hasBuffers = false;
  93317. var processBuffer = function (buf, buffer) {
  93318. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  93319. gltfRuntime.loadedBufferCount++;
  93320. if (bufferView) {
  93321. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  93322. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  93323. }
  93324. gltfRuntime.loadedBufferViews[buf] = bufferView;
  93325. }
  93326. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  93327. onLoad();
  93328. }
  93329. }, function () {
  93330. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  93331. });
  93332. };
  93333. for (var buf in gltfRuntime.buffers) {
  93334. hasBuffers = true;
  93335. var buffer = gltfRuntime.buffers[buf];
  93336. if (buffer) {
  93337. processBuffer.bind(this, buf, buffer)();
  93338. }
  93339. else {
  93340. BABYLON.Tools.Error("No buffer named: " + buf);
  93341. }
  93342. }
  93343. if (!hasBuffers) {
  93344. onLoad();
  93345. }
  93346. };
  93347. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  93348. var currentScene = gltfRuntime.currentScene;
  93349. if (currentScene) {
  93350. // Only one scene even if multiple scenes are defined
  93351. for (var i = 0; i < currentScene.nodes.length; i++) {
  93352. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  93353. }
  93354. }
  93355. else {
  93356. // Load all scenes
  93357. for (var thing in gltfRuntime.scenes) {
  93358. currentScene = gltfRuntime.scenes[thing];
  93359. for (var i = 0; i < currentScene.nodes.length; i++) {
  93360. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  93361. }
  93362. }
  93363. }
  93364. };
  93365. GLTFLoader.Extensions = {};
  93366. return GLTFLoader;
  93367. }());
  93368. GLTF1.GLTFLoader = GLTFLoader;
  93369. ;
  93370. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  93371. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  93372. })(BABYLON || (BABYLON = {}));
  93373. //# sourceMappingURL=babylon.glTFLoader.js.map
  93374. "use strict";
  93375. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93376. var BABYLON;
  93377. (function (BABYLON) {
  93378. var GLTF1;
  93379. (function (GLTF1) {
  93380. /**
  93381. * Utils functions for GLTF
  93382. */
  93383. var GLTFUtils = /** @class */ (function () {
  93384. function GLTFUtils() {
  93385. }
  93386. /**
  93387. * Sets the given "parameter" matrix
  93388. * @param scene: the {BABYLON.Scene} object
  93389. * @param source: the source node where to pick the matrix
  93390. * @param parameter: the GLTF technique parameter
  93391. * @param uniformName: the name of the shader's uniform
  93392. * @param shaderMaterial: the shader material
  93393. */
  93394. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  93395. var mat = null;
  93396. if (parameter.semantic === "MODEL") {
  93397. mat = source.getWorldMatrix();
  93398. }
  93399. else if (parameter.semantic === "PROJECTION") {
  93400. mat = scene.getProjectionMatrix();
  93401. }
  93402. else if (parameter.semantic === "VIEW") {
  93403. mat = scene.getViewMatrix();
  93404. }
  93405. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  93406. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  93407. }
  93408. else if (parameter.semantic === "MODELVIEW") {
  93409. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  93410. }
  93411. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  93412. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  93413. }
  93414. else if (parameter.semantic === "MODELINVERSE") {
  93415. mat = source.getWorldMatrix().invert();
  93416. }
  93417. else if (parameter.semantic === "VIEWINVERSE") {
  93418. mat = scene.getViewMatrix().invert();
  93419. }
  93420. else if (parameter.semantic === "PROJECTIONINVERSE") {
  93421. mat = scene.getProjectionMatrix().invert();
  93422. }
  93423. else if (parameter.semantic === "MODELVIEWINVERSE") {
  93424. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  93425. }
  93426. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  93427. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  93428. }
  93429. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  93430. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  93431. }
  93432. else {
  93433. debugger;
  93434. }
  93435. if (mat) {
  93436. switch (parameter.type) {
  93437. case GLTF1.EParameterType.FLOAT_MAT2:
  93438. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  93439. break;
  93440. case GLTF1.EParameterType.FLOAT_MAT3:
  93441. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  93442. break;
  93443. case GLTF1.EParameterType.FLOAT_MAT4:
  93444. shaderMaterial.setMatrix(uniformName, mat);
  93445. break;
  93446. default: break;
  93447. }
  93448. }
  93449. };
  93450. /**
  93451. * Sets the given "parameter" matrix
  93452. * @param shaderMaterial: the shader material
  93453. * @param uniform: the name of the shader's uniform
  93454. * @param value: the value of the uniform
  93455. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  93456. */
  93457. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  93458. switch (type) {
  93459. case GLTF1.EParameterType.FLOAT:
  93460. shaderMaterial.setFloat(uniform, value);
  93461. return true;
  93462. case GLTF1.EParameterType.FLOAT_VEC2:
  93463. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  93464. return true;
  93465. case GLTF1.EParameterType.FLOAT_VEC3:
  93466. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  93467. return true;
  93468. case GLTF1.EParameterType.FLOAT_VEC4:
  93469. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  93470. return true;
  93471. default: return false;
  93472. }
  93473. };
  93474. /**
  93475. * Returns the wrap mode of the texture
  93476. * @param mode: the mode value
  93477. */
  93478. GLTFUtils.GetWrapMode = function (mode) {
  93479. switch (mode) {
  93480. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  93481. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  93482. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  93483. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  93484. }
  93485. };
  93486. /**
  93487. * Returns the byte stride giving an accessor
  93488. * @param accessor: the GLTF accessor objet
  93489. */
  93490. GLTFUtils.GetByteStrideFromType = function (accessor) {
  93491. // Needs this function since "byteStride" isn't requiered in glTF format
  93492. var type = accessor.type;
  93493. switch (type) {
  93494. case "VEC2": return 2;
  93495. case "VEC3": return 3;
  93496. case "VEC4": return 4;
  93497. case "MAT2": return 4;
  93498. case "MAT3": return 9;
  93499. case "MAT4": return 16;
  93500. default: return 1;
  93501. }
  93502. };
  93503. /**
  93504. * Returns the texture filter mode giving a mode value
  93505. * @param mode: the filter mode value
  93506. */
  93507. GLTFUtils.GetTextureFilterMode = function (mode) {
  93508. switch (mode) {
  93509. case GLTF1.ETextureFilterType.LINEAR:
  93510. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  93511. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  93512. case GLTF1.ETextureFilterType.NEAREST:
  93513. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  93514. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  93515. }
  93516. };
  93517. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  93518. var byteOffset = bufferView.byteOffset + byteOffset;
  93519. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  93520. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  93521. throw new Error("Buffer access is out of range");
  93522. }
  93523. var buffer = loadedBufferView.buffer;
  93524. byteOffset += loadedBufferView.byteOffset;
  93525. switch (componentType) {
  93526. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  93527. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  93528. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  93529. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  93530. default: return new Float32Array(buffer, byteOffset, byteLength);
  93531. }
  93532. };
  93533. /**
  93534. * Returns a buffer from its accessor
  93535. * @param gltfRuntime: the GLTF runtime
  93536. * @param accessor: the GLTF accessor
  93537. */
  93538. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  93539. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  93540. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  93541. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  93542. };
  93543. /**
  93544. * Decodes a buffer view into a string
  93545. * @param view: the buffer view
  93546. */
  93547. GLTFUtils.DecodeBufferToText = function (view) {
  93548. var result = "";
  93549. var length = view.byteLength;
  93550. for (var i = 0; i < length; ++i) {
  93551. result += String.fromCharCode(view[i]);
  93552. }
  93553. return result;
  93554. };
  93555. /**
  93556. * Returns the default material of gltf. Related to
  93557. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  93558. * @param scene: the Babylon.js scene
  93559. */
  93560. GLTFUtils.GetDefaultMaterial = function (scene) {
  93561. if (!GLTFUtils._DefaultMaterial) {
  93562. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  93563. "precision highp float;",
  93564. "",
  93565. "uniform mat4 worldView;",
  93566. "uniform mat4 projection;",
  93567. "",
  93568. "attribute vec3 position;",
  93569. "",
  93570. "void main(void)",
  93571. "{",
  93572. " gl_Position = projection * worldView * vec4(position, 1.0);",
  93573. "}"
  93574. ].join("\n");
  93575. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  93576. "precision highp float;",
  93577. "",
  93578. "uniform vec4 u_emission;",
  93579. "",
  93580. "void main(void)",
  93581. "{",
  93582. " gl_FragColor = u_emission;",
  93583. "}"
  93584. ].join("\n");
  93585. var shaderPath = {
  93586. vertex: "GLTFDefaultMaterial",
  93587. fragment: "GLTFDefaultMaterial"
  93588. };
  93589. var options = {
  93590. attributes: ["position"],
  93591. uniforms: ["worldView", "projection", "u_emission"],
  93592. samplers: new Array(),
  93593. needAlphaBlending: false
  93594. };
  93595. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  93596. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  93597. }
  93598. return GLTFUtils._DefaultMaterial;
  93599. };
  93600. // The GLTF default material
  93601. GLTFUtils._DefaultMaterial = null;
  93602. return GLTFUtils;
  93603. }());
  93604. GLTF1.GLTFUtils = GLTFUtils;
  93605. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  93606. })(BABYLON || (BABYLON = {}));
  93607. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  93608. "use strict";
  93609. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93610. var BABYLON;
  93611. (function (BABYLON) {
  93612. var GLTF1;
  93613. (function (GLTF1) {
  93614. var GLTFLoaderExtension = /** @class */ (function () {
  93615. function GLTFLoaderExtension(name) {
  93616. this._name = name;
  93617. }
  93618. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  93619. get: function () {
  93620. return this._name;
  93621. },
  93622. enumerable: true,
  93623. configurable: true
  93624. });
  93625. /**
  93626. * Defines an override for loading the runtime
  93627. * Return true to stop further extensions from loading the runtime
  93628. */
  93629. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  93630. return false;
  93631. };
  93632. /**
  93633. * Defines an onverride for creating gltf runtime
  93634. * Return true to stop further extensions from creating the runtime
  93635. */
  93636. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  93637. return false;
  93638. };
  93639. /**
  93640. * Defines an override for loading buffers
  93641. * Return true to stop further extensions from loading this buffer
  93642. */
  93643. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  93644. return false;
  93645. };
  93646. /**
  93647. * Defines an override for loading texture buffers
  93648. * Return true to stop further extensions from loading this texture data
  93649. */
  93650. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  93651. return false;
  93652. };
  93653. /**
  93654. * Defines an override for creating textures
  93655. * Return true to stop further extensions from loading this texture
  93656. */
  93657. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  93658. return false;
  93659. };
  93660. /**
  93661. * Defines an override for loading shader strings
  93662. * Return true to stop further extensions from loading this shader data
  93663. */
  93664. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  93665. return false;
  93666. };
  93667. /**
  93668. * Defines an override for loading materials
  93669. * Return true to stop further extensions from loading this material
  93670. */
  93671. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  93672. return false;
  93673. };
  93674. // ---------
  93675. // Utilities
  93676. // ---------
  93677. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  93678. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93679. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  93680. }, function () {
  93681. setTimeout(function () {
  93682. if (!onSuccess) {
  93683. return;
  93684. }
  93685. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  93686. });
  93687. });
  93688. };
  93689. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  93690. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93691. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  93692. }, function () {
  93693. setTimeout(function () {
  93694. onSuccess();
  93695. });
  93696. });
  93697. };
  93698. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  93699. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93700. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  93701. }, function () {
  93702. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  93703. });
  93704. };
  93705. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  93706. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  93707. if (buffer) {
  93708. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  93709. }
  93710. }, onError);
  93711. };
  93712. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  93713. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93714. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  93715. }, function () {
  93716. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  93717. });
  93718. };
  93719. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  93720. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93721. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  93722. }, function () {
  93723. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  93724. });
  93725. };
  93726. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  93727. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93728. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  93729. }, function () {
  93730. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  93731. });
  93732. };
  93733. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  93734. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  93735. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  93736. }, function () {
  93737. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  93738. });
  93739. };
  93740. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  93741. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  93742. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  93743. if (func(loaderExtension)) {
  93744. return;
  93745. }
  93746. }
  93747. defaultFunc();
  93748. };
  93749. return GLTFLoaderExtension;
  93750. }());
  93751. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  93752. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  93753. })(BABYLON || (BABYLON = {}));
  93754. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  93755. "use strict";
  93756. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93757. var BABYLON;
  93758. (function (BABYLON) {
  93759. var GLTF1;
  93760. (function (GLTF1) {
  93761. var BinaryExtensionBufferName = "binary_glTF";
  93762. ;
  93763. ;
  93764. var GLTFBinaryExtension = /** @class */ (function (_super) {
  93765. __extends(GLTFBinaryExtension, _super);
  93766. function GLTFBinaryExtension() {
  93767. return _super.call(this, "KHR_binary_glTF") || this;
  93768. }
  93769. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  93770. var extensionsUsed = data.json.extensionsUsed;
  93771. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  93772. return false;
  93773. }
  93774. this._bin = data.bin;
  93775. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  93776. return true;
  93777. };
  93778. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  93779. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  93780. return false;
  93781. }
  93782. if (id !== BinaryExtensionBufferName) {
  93783. return false;
  93784. }
  93785. onSuccess(this._bin);
  93786. return true;
  93787. };
  93788. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  93789. var texture = gltfRuntime.textures[id];
  93790. var source = gltfRuntime.images[texture.source];
  93791. if (!source.extensions || !(this.name in source.extensions)) {
  93792. return false;
  93793. }
  93794. var sourceExt = source.extensions[this.name];
  93795. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  93796. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  93797. onSuccess(buffer);
  93798. return true;
  93799. };
  93800. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  93801. var shader = gltfRuntime.shaders[id];
  93802. if (!shader.extensions || !(this.name in shader.extensions)) {
  93803. return false;
  93804. }
  93805. var binaryExtensionShader = shader.extensions[this.name];
  93806. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  93807. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  93808. setTimeout(function () {
  93809. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  93810. onSuccess(shaderString);
  93811. });
  93812. return true;
  93813. };
  93814. return GLTFBinaryExtension;
  93815. }(GLTF1.GLTFLoaderExtension));
  93816. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  93817. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  93818. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  93819. })(BABYLON || (BABYLON = {}));
  93820. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  93821. "use strict";
  93822. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93823. var BABYLON;
  93824. (function (BABYLON) {
  93825. var GLTF1;
  93826. (function (GLTF1) {
  93827. ;
  93828. ;
  93829. ;
  93830. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  93831. __extends(GLTFMaterialsCommonExtension, _super);
  93832. function GLTFMaterialsCommonExtension() {
  93833. return _super.call(this, "KHR_materials_common") || this;
  93834. }
  93835. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  93836. if (!gltfRuntime.extensions)
  93837. return false;
  93838. var extension = gltfRuntime.extensions[this.name];
  93839. if (!extension)
  93840. return false;
  93841. // Create lights
  93842. var lights = extension.lights;
  93843. if (lights) {
  93844. for (var thing in lights) {
  93845. var light = lights[thing];
  93846. switch (light.type) {
  93847. case "ambient":
  93848. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  93849. var ambient = light.ambient;
  93850. if (ambient) {
  93851. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  93852. }
  93853. break;
  93854. case "point":
  93855. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  93856. var point = light.point;
  93857. if (point) {
  93858. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  93859. }
  93860. break;
  93861. case "directional":
  93862. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  93863. var directional = light.directional;
  93864. if (directional) {
  93865. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  93866. }
  93867. break;
  93868. case "spot":
  93869. var spot = light.spot;
  93870. if (spot) {
  93871. 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);
  93872. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  93873. }
  93874. break;
  93875. default:
  93876. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  93877. break;
  93878. }
  93879. }
  93880. }
  93881. return false;
  93882. };
  93883. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  93884. var material = gltfRuntime.materials[id];
  93885. if (!material || !material.extensions)
  93886. return false;
  93887. var extension = material.extensions[this.name];
  93888. if (!extension)
  93889. return false;
  93890. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  93891. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  93892. if (extension.technique === "CONSTANT") {
  93893. standardMaterial.disableLighting = true;
  93894. }
  93895. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  93896. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  93897. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  93898. // Ambient
  93899. if (typeof extension.values.ambient === "string") {
  93900. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  93901. }
  93902. else {
  93903. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  93904. }
  93905. // Diffuse
  93906. if (typeof extension.values.diffuse === "string") {
  93907. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  93908. }
  93909. else {
  93910. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  93911. }
  93912. // Emission
  93913. if (typeof extension.values.emission === "string") {
  93914. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  93915. }
  93916. else {
  93917. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  93918. }
  93919. // Specular
  93920. if (typeof extension.values.specular === "string") {
  93921. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  93922. }
  93923. else {
  93924. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  93925. }
  93926. return true;
  93927. };
  93928. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  93929. // Create buffer from texture url
  93930. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  93931. // Create texture from buffer
  93932. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  93933. }, onError);
  93934. };
  93935. return GLTFMaterialsCommonExtension;
  93936. }(GLTF1.GLTFLoaderExtension));
  93937. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  93938. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  93939. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  93940. })(BABYLON || (BABYLON = {}));
  93941. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  93942. "use strict";
  93943. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93944. var BABYLON;
  93945. (function (BABYLON) {
  93946. var GLTF2;
  93947. (function (GLTF2) {
  93948. var ArrayItem = /** @class */ (function () {
  93949. function ArrayItem() {
  93950. }
  93951. ArrayItem.Assign = function (values) {
  93952. if (values) {
  93953. for (var index = 0; index < values.length; index++) {
  93954. values[index]._index = index;
  93955. }
  93956. }
  93957. };
  93958. return ArrayItem;
  93959. }());
  93960. GLTF2.ArrayItem = ArrayItem;
  93961. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  93962. })(BABYLON || (BABYLON = {}));
  93963. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  93964. "use strict";
  93965. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93966. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  93967. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  93968. "use strict";
  93969. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  93970. var BABYLON;
  93971. (function (BABYLON) {
  93972. var GLTF2;
  93973. (function (GLTF2) {
  93974. var GLTFLoader = /** @class */ (function () {
  93975. function GLTFLoader() {
  93976. this._completePromises = new Array();
  93977. this._disposed = false;
  93978. this._state = null;
  93979. this._extensions = {};
  93980. this._defaultSampler = {};
  93981. this._defaultBabylonMaterials = {};
  93982. this._requests = new Array();
  93983. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  93984. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  93985. this.compileMaterials = false;
  93986. this.useClipPlane = false;
  93987. this.compileShadowGenerators = false;
  93988. this.onDisposeObservable = new BABYLON.Observable();
  93989. this.onMeshLoadedObservable = new BABYLON.Observable();
  93990. this.onTextureLoadedObservable = new BABYLON.Observable();
  93991. this.onMaterialLoadedObservable = new BABYLON.Observable();
  93992. this.onAnimationGroupLoadedObservable = new BABYLON.Observable();
  93993. this.onExtensionLoadedObservable = new BABYLON.Observable();
  93994. this.onCompleteObservable = new BABYLON.Observable();
  93995. }
  93996. GLTFLoader._Register = function (name, factory) {
  93997. if (GLTFLoader._Factories[name]) {
  93998. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  93999. return;
  94000. }
  94001. GLTFLoader._Factories[name] = factory;
  94002. // Keep the order of registration so that extensions registered first are called first.
  94003. GLTFLoader._Names.push(name);
  94004. };
  94005. Object.defineProperty(GLTFLoader.prototype, "state", {
  94006. get: function () {
  94007. return this._state;
  94008. },
  94009. enumerable: true,
  94010. configurable: true
  94011. });
  94012. GLTFLoader.prototype.dispose = function () {
  94013. if (this._disposed) {
  94014. return;
  94015. }
  94016. this._disposed = true;
  94017. this.onDisposeObservable.notifyObservers(this);
  94018. this.onDisposeObservable.clear();
  94019. this._clear();
  94020. };
  94021. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  94022. var _this = this;
  94023. return Promise.resolve().then(function () {
  94024. var nodes = null;
  94025. if (meshesNames) {
  94026. var nodeMap_1 = {};
  94027. if (_this._gltf.nodes) {
  94028. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  94029. var node = _a[_i];
  94030. if (node.name) {
  94031. nodeMap_1[node.name] = node;
  94032. }
  94033. }
  94034. }
  94035. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  94036. nodes = names.map(function (name) {
  94037. var node = nodeMap_1[name];
  94038. if (!node) {
  94039. throw new Error("Failed to find node '" + name + "'");
  94040. }
  94041. return node;
  94042. });
  94043. }
  94044. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  94045. return {
  94046. meshes: _this._getMeshes(),
  94047. particleSystems: [],
  94048. skeletons: _this._getSkeletons(),
  94049. };
  94050. });
  94051. });
  94052. };
  94053. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  94054. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  94055. };
  94056. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  94057. var _this = this;
  94058. return Promise.resolve().then(function () {
  94059. _this._loadExtensions();
  94060. _this._babylonScene = scene;
  94061. _this._rootUrl = rootUrl;
  94062. _this._progressCallback = onProgress;
  94063. _this._state = BABYLON.GLTFLoaderState.Loading;
  94064. _this._loadData(data);
  94065. _this._checkExtensions();
  94066. var promises = new Array();
  94067. if (nodes) {
  94068. promises.push(_this._loadNodesAsync(nodes));
  94069. }
  94070. else {
  94071. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  94072. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  94073. }
  94074. if (_this.compileMaterials) {
  94075. promises.push(_this._compileMaterialsAsync());
  94076. }
  94077. if (_this.compileShadowGenerators) {
  94078. promises.push(_this._compileShadowGeneratorsAsync());
  94079. }
  94080. var resultPromise = Promise.all(promises).then(function () {
  94081. _this._state = BABYLON.GLTFLoaderState.Ready;
  94082. _this._startAnimations();
  94083. });
  94084. resultPromise.then(function () {
  94085. _this._rootBabylonMesh.setEnabled(true);
  94086. BABYLON.Tools.SetImmediate(function () {
  94087. if (!_this._disposed) {
  94088. Promise.all(_this._completePromises).then(function () {
  94089. _this._state = BABYLON.GLTFLoaderState.Complete;
  94090. _this.onCompleteObservable.notifyObservers(_this);
  94091. _this.onCompleteObservable.clear();
  94092. _this._clear();
  94093. }).catch(function (error) {
  94094. BABYLON.Tools.Error("glTF Loader: " + error.message);
  94095. _this._clear();
  94096. });
  94097. }
  94098. });
  94099. });
  94100. return resultPromise;
  94101. }).catch(function (error) {
  94102. BABYLON.Tools.Error("glTF Loader: " + error.message);
  94103. _this._clear();
  94104. throw error;
  94105. });
  94106. };
  94107. GLTFLoader.prototype._loadExtensions = function () {
  94108. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  94109. var name_1 = _a[_i];
  94110. var extension = GLTFLoader._Factories[name_1](this);
  94111. this._extensions[name_1] = extension;
  94112. this.onExtensionLoadedObservable.notifyObservers(extension);
  94113. }
  94114. this.onExtensionLoadedObservable.clear();
  94115. };
  94116. GLTFLoader.prototype._loadData = function (data) {
  94117. this._gltf = data.json;
  94118. this._setupData();
  94119. if (data.bin) {
  94120. var buffers = this._gltf.buffers;
  94121. if (buffers && buffers[0] && !buffers[0].uri) {
  94122. var binaryBuffer = buffers[0];
  94123. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  94124. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  94125. }
  94126. binaryBuffer._data = Promise.resolve(data.bin);
  94127. }
  94128. else {
  94129. BABYLON.Tools.Warn("Unexpected BIN chunk");
  94130. }
  94131. }
  94132. };
  94133. GLTFLoader.prototype._setupData = function () {
  94134. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  94135. GLTF2.ArrayItem.Assign(this._gltf.animations);
  94136. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  94137. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  94138. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  94139. GLTF2.ArrayItem.Assign(this._gltf.images);
  94140. GLTF2.ArrayItem.Assign(this._gltf.materials);
  94141. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  94142. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  94143. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  94144. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  94145. GLTF2.ArrayItem.Assign(this._gltf.skins);
  94146. GLTF2.ArrayItem.Assign(this._gltf.textures);
  94147. if (this._gltf.nodes) {
  94148. var nodeParents = {};
  94149. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  94150. var node = _a[_i];
  94151. if (node.children) {
  94152. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  94153. var index = _c[_b];
  94154. nodeParents[index] = node._index;
  94155. }
  94156. }
  94157. }
  94158. var rootNode = this._createRootNode();
  94159. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  94160. var node = _e[_d];
  94161. var parentIndex = nodeParents[node._index];
  94162. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  94163. }
  94164. }
  94165. };
  94166. GLTFLoader.prototype._checkExtensions = function () {
  94167. if (this._gltf.extensionsRequired) {
  94168. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  94169. var name_2 = _a[_i];
  94170. var extension = this._extensions[name_2];
  94171. if (!extension || !extension.enabled) {
  94172. throw new Error("Require extension " + name_2 + " is not available");
  94173. }
  94174. }
  94175. }
  94176. };
  94177. GLTFLoader.prototype._createRootNode = function () {
  94178. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  94179. this._rootBabylonMesh.setEnabled(false);
  94180. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  94181. switch (this.coordinateSystemMode) {
  94182. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  94183. if (!this._babylonScene.useRightHandedSystem) {
  94184. rootNode.rotation = [0, 1, 0, 0];
  94185. rootNode.scale = [1, 1, -1];
  94186. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  94187. }
  94188. break;
  94189. }
  94190. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  94191. this._babylonScene.useRightHandedSystem = true;
  94192. break;
  94193. }
  94194. default: {
  94195. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  94196. }
  94197. }
  94198. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  94199. return rootNode;
  94200. };
  94201. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  94202. var promises = new Array();
  94203. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  94204. var node = nodes_1[_i];
  94205. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  94206. }
  94207. promises.push(this._loadAnimationsAsync());
  94208. return Promise.all(promises).then(function () { });
  94209. };
  94210. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  94211. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  94212. if (promise) {
  94213. return promise;
  94214. }
  94215. var promises = new Array();
  94216. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  94217. var index = _a[_i];
  94218. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  94219. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  94220. }
  94221. promises.push(this._loadAnimationsAsync());
  94222. return Promise.all(promises).then(function () { });
  94223. };
  94224. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  94225. if (node._primitiveBabylonMeshes) {
  94226. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  94227. var babylonMesh = _a[_i];
  94228. callback(babylonMesh);
  94229. }
  94230. }
  94231. else {
  94232. callback(node._babylonMesh);
  94233. }
  94234. };
  94235. GLTFLoader.prototype._getMeshes = function () {
  94236. var meshes = new Array();
  94237. // Root mesh is always first.
  94238. meshes.push(this._rootBabylonMesh);
  94239. var nodes = this._gltf.nodes;
  94240. if (nodes) {
  94241. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  94242. var node = nodes_2[_i];
  94243. if (node._babylonMesh) {
  94244. meshes.push(node._babylonMesh);
  94245. }
  94246. if (node._primitiveBabylonMeshes) {
  94247. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  94248. var babylonMesh = _b[_a];
  94249. meshes.push(babylonMesh);
  94250. }
  94251. }
  94252. }
  94253. }
  94254. return meshes;
  94255. };
  94256. GLTFLoader.prototype._getSkeletons = function () {
  94257. var skeletons = new Array();
  94258. var skins = this._gltf.skins;
  94259. if (skins) {
  94260. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  94261. var skin = skins_1[_i];
  94262. if (skin._babylonSkeleton) {
  94263. skeletons.push(skin._babylonSkeleton);
  94264. }
  94265. }
  94266. }
  94267. return skeletons;
  94268. };
  94269. GLTFLoader.prototype._startAnimations = function () {
  94270. var animations = this._gltf.animations;
  94271. if (!animations) {
  94272. return;
  94273. }
  94274. switch (this.animationStartMode) {
  94275. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  94276. // do nothing
  94277. break;
  94278. }
  94279. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  94280. var animation = animations[0];
  94281. animation._babylonAnimationGroup.start(true);
  94282. break;
  94283. }
  94284. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  94285. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  94286. var animation = animations_1[_i];
  94287. animation._babylonAnimationGroup.start(true);
  94288. }
  94289. break;
  94290. }
  94291. default: {
  94292. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  94293. return;
  94294. }
  94295. }
  94296. };
  94297. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  94298. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  94299. if (promise) {
  94300. return promise;
  94301. }
  94302. if (node._babylonMesh) {
  94303. throw new Error(context + ": Invalid recursive node hierarchy");
  94304. }
  94305. var promises = new Array();
  94306. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  94307. node._babylonMesh = babylonMesh;
  94308. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  94309. node._babylonAnimationTargets.push(babylonMesh);
  94310. GLTFLoader._LoadTransform(node, babylonMesh);
  94311. if (node.mesh != undefined) {
  94312. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  94313. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  94314. }
  94315. if (node.children) {
  94316. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  94317. var index = _a[_i];
  94318. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  94319. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  94320. }
  94321. }
  94322. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  94323. return Promise.all(promises).then(function () { });
  94324. };
  94325. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  94326. // TODO: instancing
  94327. var _this = this;
  94328. var promises = new Array();
  94329. var primitives = mesh.primitives;
  94330. if (!primitives || primitives.length === 0) {
  94331. throw new Error(context + ": Primitives are missing");
  94332. }
  94333. GLTF2.ArrayItem.Assign(primitives);
  94334. if (primitives.length === 1) {
  94335. var primitive = primitives[0];
  94336. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  94337. }
  94338. else {
  94339. node._primitiveBabylonMeshes = [];
  94340. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  94341. var primitive = primitives_1[_i];
  94342. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  94343. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  94344. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  94345. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  94346. }
  94347. }
  94348. if (node.skin != undefined) {
  94349. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  94350. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  94351. }
  94352. return Promise.all(promises).then(function () {
  94353. _this._forEachPrimitive(node, function (babylonMesh) {
  94354. babylonMesh._refreshBoundingInfo(true);
  94355. });
  94356. });
  94357. };
  94358. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  94359. var _this = this;
  94360. var promises = new Array();
  94361. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  94362. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  94363. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  94364. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  94365. }));
  94366. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  94367. if (primitive.material == undefined) {
  94368. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  94369. }
  94370. else {
  94371. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  94372. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  94373. babylonMesh.material = babylonMaterial;
  94374. }));
  94375. }
  94376. return Promise.all(promises).then(function () { });
  94377. };
  94378. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  94379. var _this = this;
  94380. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  94381. if (promise) {
  94382. return promise;
  94383. }
  94384. var attributes = primitive.attributes;
  94385. if (!attributes) {
  94386. throw new Error(context + ": Attributes are missing");
  94387. }
  94388. var promises = new Array();
  94389. var babylonVertexData = new BABYLON.VertexData();
  94390. if (primitive.indices == undefined) {
  94391. var positionAccessorIndex = attributes["POSITION"];
  94392. if (positionAccessorIndex != undefined) {
  94393. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  94394. babylonVertexData.indices = new Uint32Array(accessor.count);
  94395. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  94396. babylonVertexData.indices[i] = i;
  94397. }
  94398. }
  94399. }
  94400. else {
  94401. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  94402. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  94403. babylonVertexData.indices = data;
  94404. }));
  94405. }
  94406. var loadAttribute = function (attribute, kind) {
  94407. if (attributes[attribute] == undefined) {
  94408. return;
  94409. }
  94410. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  94411. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  94412. babylonMesh._delayInfo.push(kind);
  94413. }
  94414. if (attribute === "COLOR_0") {
  94415. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  94416. babylonMesh.hasVertexAlpha = true;
  94417. }
  94418. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  94419. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  94420. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  94421. if (attribute === "COLOR_0" && accessor.type === "VEC3") {
  94422. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  94423. }
  94424. babylonVertexData.set(attributeData, kind);
  94425. }));
  94426. };
  94427. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  94428. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  94429. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  94430. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  94431. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  94432. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  94433. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  94434. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  94435. return Promise.all(promises).then(function () {
  94436. return babylonVertexData;
  94437. });
  94438. };
  94439. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  94440. if (!primitive.targets) {
  94441. return;
  94442. }
  94443. if (node._numMorphTargets == undefined) {
  94444. node._numMorphTargets = primitive.targets.length;
  94445. }
  94446. else if (primitive.targets.length !== node._numMorphTargets) {
  94447. throw new Error(context + ": Primitives do not have the same number of targets");
  94448. }
  94449. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  94450. for (var index = 0; index < primitive.targets.length; index++) {
  94451. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  94452. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  94453. // TODO: tell the target whether it has positions, normals, tangents
  94454. }
  94455. };
  94456. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  94457. if (!primitive.targets) {
  94458. return Promise.resolve();
  94459. }
  94460. var promises = new Array();
  94461. var morphTargetManager = babylonMesh.morphTargetManager;
  94462. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  94463. var babylonMorphTarget = morphTargetManager.getTarget(index);
  94464. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  94465. }
  94466. return Promise.all(promises).then(function () { });
  94467. };
  94468. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  94469. var _this = this;
  94470. var promises = new Array();
  94471. var loadAttribute = function (attribute, setData) {
  94472. if (attributes[attribute] == undefined) {
  94473. return;
  94474. }
  94475. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  94476. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  94477. setData(data);
  94478. }));
  94479. };
  94480. loadAttribute("POSITION", function (data) {
  94481. if (babylonVertexData.positions) {
  94482. for (var i = 0; i < data.length; i++) {
  94483. data[i] += babylonVertexData.positions[i];
  94484. }
  94485. babylonMorphTarget.setPositions(data);
  94486. }
  94487. });
  94488. loadAttribute("NORMAL", function (data) {
  94489. if (babylonVertexData.normals) {
  94490. for (var i = 0; i < data.length; i++) {
  94491. data[i] += babylonVertexData.normals[i];
  94492. }
  94493. babylonMorphTarget.setNormals(data);
  94494. }
  94495. });
  94496. loadAttribute("TANGENT", function (data) {
  94497. if (babylonVertexData.tangents) {
  94498. // Tangent data for morph targets is stored as xyz delta.
  94499. // The vertexData.tangent is stored as xyzw.
  94500. // So we need to skip every fourth vertexData.tangent.
  94501. for (var i = 0, j = 0; i < data.length; i++) {
  94502. data[i] += babylonVertexData.tangents[j++];
  94503. if ((i + 1) % 3 == 0) {
  94504. j++;
  94505. }
  94506. }
  94507. babylonMorphTarget.setTangents(data);
  94508. }
  94509. });
  94510. return Promise.all(promises).then(function () { });
  94511. };
  94512. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  94513. if (accessor.componentType == 5126 /* FLOAT */) {
  94514. return data;
  94515. }
  94516. var factor = 1;
  94517. if (accessor.normalized) {
  94518. switch (accessor.componentType) {
  94519. case 5121 /* UNSIGNED_BYTE */: {
  94520. factor = 1 / 255;
  94521. break;
  94522. }
  94523. case 5123 /* UNSIGNED_SHORT */: {
  94524. factor = 1 / 65535;
  94525. break;
  94526. }
  94527. default: {
  94528. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  94529. }
  94530. }
  94531. }
  94532. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  94533. for (var i = 0; i < result.length; i++) {
  94534. result[i] = data[i] * factor;
  94535. }
  94536. return result;
  94537. };
  94538. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  94539. var result = new Float32Array(data.length / 3 * 4);
  94540. var offset = 0;
  94541. for (var i = 0; i < result.length; i++) {
  94542. if ((i + 1) % 4 === 0) {
  94543. result[i] = 1;
  94544. }
  94545. else {
  94546. result[i] = data[offset++];
  94547. }
  94548. }
  94549. return result;
  94550. };
  94551. GLTFLoader._LoadTransform = function (node, babylonNode) {
  94552. var position = BABYLON.Vector3.Zero();
  94553. var rotation = BABYLON.Quaternion.Identity();
  94554. var scaling = BABYLON.Vector3.One();
  94555. if (node.matrix) {
  94556. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  94557. matrix.decompose(scaling, rotation, position);
  94558. }
  94559. else {
  94560. if (node.translation)
  94561. position = BABYLON.Vector3.FromArray(node.translation);
  94562. if (node.rotation)
  94563. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  94564. if (node.scale)
  94565. scaling = BABYLON.Vector3.FromArray(node.scale);
  94566. }
  94567. babylonNode.position = position;
  94568. babylonNode.rotationQuaternion = rotation;
  94569. babylonNode.scaling = scaling;
  94570. };
  94571. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  94572. var _this = this;
  94573. var assignSkeleton = function () {
  94574. _this._forEachPrimitive(node, function (babylonMesh) {
  94575. babylonMesh.skeleton = skin._babylonSkeleton;
  94576. });
  94577. node._babylonMesh.parent = _this._rootBabylonMesh;
  94578. node._babylonMesh.position = BABYLON.Vector3.Zero();
  94579. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  94580. node._babylonMesh.scaling = BABYLON.Vector3.One();
  94581. };
  94582. if (skin._loaded) {
  94583. return skin._loaded.then(function () {
  94584. assignSkeleton();
  94585. });
  94586. }
  94587. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  94588. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  94589. var skeletonId = "skeleton" + skin._index;
  94590. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  94591. skin._babylonSkeleton = babylonSkeleton;
  94592. _this._loadBones(context, skin, inverseBindMatricesData);
  94593. assignSkeleton();
  94594. }));
  94595. };
  94596. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  94597. if (skin.inverseBindMatrices == undefined) {
  94598. return Promise.resolve(null);
  94599. }
  94600. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  94601. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  94602. return data;
  94603. });
  94604. };
  94605. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  94606. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  94607. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  94608. node._babylonAnimationTargets.push(babylonBone);
  94609. return babylonBone;
  94610. };
  94611. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  94612. var babylonBones = {};
  94613. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  94614. var index = _a[_i];
  94615. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  94616. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  94617. }
  94618. };
  94619. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  94620. var babylonBone = babylonBones[node._index];
  94621. if (babylonBone) {
  94622. return babylonBone;
  94623. }
  94624. var boneIndex = skin.joints.indexOf(node._index);
  94625. var baseMatrix = BABYLON.Matrix.Identity();
  94626. if (inverseBindMatricesData && boneIndex !== -1) {
  94627. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  94628. baseMatrix.invertToRef(baseMatrix);
  94629. }
  94630. var babylonParentBone = null;
  94631. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  94632. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  94633. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  94634. }
  94635. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  94636. babylonBones[node._index] = babylonBone;
  94637. return babylonBone;
  94638. };
  94639. GLTFLoader.prototype._getNodeMatrix = function (node) {
  94640. return node.matrix ?
  94641. BABYLON.Matrix.FromArray(node.matrix) :
  94642. 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());
  94643. };
  94644. GLTFLoader.prototype._loadAnimationsAsync = function () {
  94645. var animations = this._gltf.animations;
  94646. if (!animations) {
  94647. return Promise.resolve();
  94648. }
  94649. var promises = new Array();
  94650. for (var index = 0; index < animations.length; index++) {
  94651. var animation = animations[index];
  94652. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  94653. }
  94654. return Promise.all(promises).then(function () { });
  94655. };
  94656. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  94657. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  94658. animation._babylonAnimationGroup = babylonAnimationGroup;
  94659. var promises = new Array();
  94660. GLTF2.ArrayItem.Assign(animation.channels);
  94661. GLTF2.ArrayItem.Assign(animation.samplers);
  94662. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  94663. var channel = _a[_i];
  94664. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  94665. }
  94666. this.onAnimationGroupLoadedObservable.notifyObservers(babylonAnimationGroup);
  94667. return Promise.all(promises).then(function () {
  94668. babylonAnimationGroup.normalize();
  94669. });
  94670. };
  94671. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  94672. var _this = this;
  94673. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  94674. if (!targetNode._babylonMesh || targetNode.skin != undefined) {
  94675. return Promise.resolve();
  94676. }
  94677. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  94678. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  94679. var targetPath;
  94680. var animationType;
  94681. switch (channel.target.path) {
  94682. case "translation" /* TRANSLATION */: {
  94683. targetPath = "position";
  94684. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  94685. break;
  94686. }
  94687. case "rotation" /* ROTATION */: {
  94688. targetPath = "rotationQuaternion";
  94689. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  94690. break;
  94691. }
  94692. case "scale" /* SCALE */: {
  94693. targetPath = "scaling";
  94694. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  94695. break;
  94696. }
  94697. case "weights" /* WEIGHTS */: {
  94698. targetPath = "influence";
  94699. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  94700. break;
  94701. }
  94702. default: {
  94703. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  94704. }
  94705. }
  94706. var outputBufferOffset = 0;
  94707. var getNextOutputValue;
  94708. switch (targetPath) {
  94709. case "position": {
  94710. getNextOutputValue = function () {
  94711. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  94712. outputBufferOffset += 3;
  94713. return value;
  94714. };
  94715. break;
  94716. }
  94717. case "rotationQuaternion": {
  94718. getNextOutputValue = function () {
  94719. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  94720. outputBufferOffset += 4;
  94721. return value;
  94722. };
  94723. break;
  94724. }
  94725. case "scaling": {
  94726. getNextOutputValue = function () {
  94727. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  94728. outputBufferOffset += 3;
  94729. return value;
  94730. };
  94731. break;
  94732. }
  94733. case "influence": {
  94734. getNextOutputValue = function () {
  94735. var value = new Array(targetNode._numMorphTargets);
  94736. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  94737. value[i] = data.output[outputBufferOffset++];
  94738. }
  94739. return value;
  94740. };
  94741. break;
  94742. }
  94743. }
  94744. var getNextKey;
  94745. switch (data.interpolation) {
  94746. case "STEP" /* STEP */: {
  94747. getNextKey = function (frameIndex) { return ({
  94748. frame: data.input[frameIndex],
  94749. value: getNextOutputValue(),
  94750. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  94751. }); };
  94752. break;
  94753. }
  94754. case "LINEAR" /* LINEAR */: {
  94755. getNextKey = function (frameIndex) { return ({
  94756. frame: data.input[frameIndex],
  94757. value: getNextOutputValue()
  94758. }); };
  94759. break;
  94760. }
  94761. case "CUBICSPLINE" /* CUBICSPLINE */: {
  94762. getNextKey = function (frameIndex) { return ({
  94763. frame: data.input[frameIndex],
  94764. inTangent: getNextOutputValue(),
  94765. value: getNextOutputValue(),
  94766. outTangent: getNextOutputValue()
  94767. }); };
  94768. break;
  94769. }
  94770. }
  94771. var keys = new Array(data.input.length);
  94772. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  94773. keys[frameIndex] = getNextKey(frameIndex);
  94774. }
  94775. if (targetPath === "influence") {
  94776. var _loop_1 = function (targetIndex) {
  94777. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  94778. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  94779. babylonAnimation.setKeys(keys.map(function (key) { return ({
  94780. frame: key.frame,
  94781. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  94782. value: key.value[targetIndex],
  94783. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  94784. }); }));
  94785. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  94786. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  94787. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  94788. });
  94789. };
  94790. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  94791. _loop_1(targetIndex);
  94792. }
  94793. }
  94794. else {
  94795. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  94796. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  94797. babylonAnimation.setKeys(keys);
  94798. if (targetNode._babylonAnimationTargets) {
  94799. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  94800. var target = _a[_i];
  94801. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  94802. }
  94803. }
  94804. }
  94805. });
  94806. };
  94807. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  94808. if (sampler._data) {
  94809. return sampler._data;
  94810. }
  94811. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  94812. switch (interpolation) {
  94813. case "STEP" /* STEP */:
  94814. case "LINEAR" /* LINEAR */:
  94815. case "CUBICSPLINE" /* CUBICSPLINE */: {
  94816. break;
  94817. }
  94818. default: {
  94819. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  94820. }
  94821. }
  94822. var inputData;
  94823. var outputData;
  94824. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  94825. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  94826. sampler._data = Promise.all([
  94827. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  94828. inputData = data;
  94829. }),
  94830. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  94831. outputData = data;
  94832. })
  94833. ]).then(function () {
  94834. return {
  94835. input: inputData,
  94836. interpolation: interpolation,
  94837. output: outputData,
  94838. };
  94839. });
  94840. return sampler._data;
  94841. };
  94842. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  94843. if (buffer._data) {
  94844. return buffer._data;
  94845. }
  94846. if (!buffer.uri) {
  94847. throw new Error(context + ": Uri is missing");
  94848. }
  94849. buffer._data = this._loadUriAsync(context, buffer.uri);
  94850. return buffer._data;
  94851. };
  94852. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  94853. if (bufferView._data) {
  94854. return bufferView._data;
  94855. }
  94856. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  94857. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  94858. try {
  94859. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  94860. }
  94861. catch (e) {
  94862. throw new Error(context + ": " + e.message);
  94863. }
  94864. });
  94865. return bufferView._data;
  94866. };
  94867. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  94868. var _this = this;
  94869. if (accessor.sparse) {
  94870. throw new Error(context + ": Sparse accessors are not currently supported");
  94871. }
  94872. if (accessor._data) {
  94873. return accessor._data;
  94874. }
  94875. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  94876. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  94877. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  94878. var byteOffset = accessor.byteOffset || 0;
  94879. var byteStride = bufferView.byteStride;
  94880. if (byteStride === 0) {
  94881. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  94882. }
  94883. try {
  94884. switch (accessor.componentType) {
  94885. case 5120 /* BYTE */: {
  94886. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94887. }
  94888. case 5121 /* UNSIGNED_BYTE */: {
  94889. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94890. }
  94891. case 5122 /* SHORT */: {
  94892. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94893. }
  94894. case 5123 /* UNSIGNED_SHORT */: {
  94895. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94896. }
  94897. case 5125 /* UNSIGNED_INT */: {
  94898. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94899. }
  94900. case 5126 /* FLOAT */: {
  94901. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  94902. }
  94903. default: {
  94904. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  94905. }
  94906. }
  94907. }
  94908. catch (e) {
  94909. throw new Error(context + ": " + e.messsage);
  94910. }
  94911. });
  94912. return accessor._data;
  94913. };
  94914. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  94915. byteOffset += data.byteOffset;
  94916. var targetLength = count * numComponents;
  94917. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  94918. return new typedArray(data.buffer, byteOffset, targetLength);
  94919. }
  94920. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  94921. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  94922. var targetBuffer = new typedArray(targetLength);
  94923. var sourceIndex = 0;
  94924. var targetIndex = 0;
  94925. while (targetIndex < targetLength) {
  94926. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  94927. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  94928. targetIndex++;
  94929. }
  94930. sourceIndex += elementStride;
  94931. }
  94932. return targetBuffer;
  94933. };
  94934. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  94935. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  94936. if (!babylonMaterial) {
  94937. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  94938. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  94939. babylonMaterial.metallic = 1;
  94940. babylonMaterial.roughness = 1;
  94941. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  94942. }
  94943. return babylonMaterial;
  94944. };
  94945. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  94946. var promises = new Array();
  94947. // Ensure metallic workflow
  94948. babylonMaterial.metallic = 1;
  94949. babylonMaterial.roughness = 1;
  94950. var properties = material.pbrMetallicRoughness;
  94951. if (properties) {
  94952. if (properties.baseColorFactor) {
  94953. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  94954. babylonMaterial.alpha = properties.baseColorFactor[3];
  94955. }
  94956. else {
  94957. babylonMaterial.albedoColor = BABYLON.Color3.White();
  94958. }
  94959. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  94960. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  94961. if (properties.baseColorTexture) {
  94962. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  94963. babylonMaterial.albedoTexture = texture;
  94964. }));
  94965. }
  94966. if (properties.metallicRoughnessTexture) {
  94967. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  94968. babylonMaterial.metallicTexture = texture;
  94969. }));
  94970. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  94971. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  94972. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  94973. }
  94974. }
  94975. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  94976. return Promise.all(promises).then(function () { });
  94977. };
  94978. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  94979. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  94980. if (promise) {
  94981. return promise;
  94982. }
  94983. material._babylonData = material._babylonData || {};
  94984. var babylonData = material._babylonData[babylonDrawMode];
  94985. if (!babylonData) {
  94986. var promises = new Array();
  94987. var name_3 = material.name || "materialSG_" + material._index;
  94988. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  94989. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  94990. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  94991. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  94992. babylonData = {
  94993. material: babylonMaterial,
  94994. meshes: [],
  94995. loaded: Promise.all(promises).then(function () { })
  94996. };
  94997. material._babylonData[babylonDrawMode] = babylonData;
  94998. }
  94999. babylonData.meshes.push(babylonMesh);
  95000. assign(babylonData.material);
  95001. return babylonData.loaded;
  95002. };
  95003. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  95004. var babylonMaterial = new type(name, this._babylonScene);
  95005. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  95006. babylonMaterial.fillMode = drawMode;
  95007. return babylonMaterial;
  95008. };
  95009. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  95010. var promises = new Array();
  95011. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  95012. if (material.doubleSided) {
  95013. babylonMaterial.backFaceCulling = false;
  95014. babylonMaterial.twoSidedLighting = true;
  95015. }
  95016. if (material.normalTexture) {
  95017. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  95018. babylonMaterial.bumpTexture = texture;
  95019. }));
  95020. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  95021. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  95022. if (material.normalTexture.scale != undefined) {
  95023. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  95024. }
  95025. }
  95026. if (material.occlusionTexture) {
  95027. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  95028. babylonMaterial.ambientTexture = texture;
  95029. }));
  95030. babylonMaterial.useAmbientInGrayScale = true;
  95031. if (material.occlusionTexture.strength != undefined) {
  95032. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  95033. }
  95034. }
  95035. if (material.emissiveTexture) {
  95036. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  95037. babylonMaterial.emissiveTexture = texture;
  95038. }));
  95039. }
  95040. return Promise.all(promises).then(function () { });
  95041. };
  95042. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  95043. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  95044. switch (alphaMode) {
  95045. case "OPAQUE" /* OPAQUE */: {
  95046. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  95047. break;
  95048. }
  95049. case "MASK" /* MASK */: {
  95050. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  95051. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  95052. if (babylonMaterial.albedoTexture) {
  95053. babylonMaterial.albedoTexture.hasAlpha = true;
  95054. }
  95055. break;
  95056. }
  95057. case "BLEND" /* BLEND */: {
  95058. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  95059. if (babylonMaterial.albedoTexture) {
  95060. babylonMaterial.albedoTexture.hasAlpha = true;
  95061. babylonMaterial.useAlphaFromAlbedoTexture = true;
  95062. }
  95063. break;
  95064. }
  95065. default: {
  95066. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  95067. }
  95068. }
  95069. };
  95070. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  95071. var _this = this;
  95072. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  95073. context = "#/textures/" + textureInfo.index;
  95074. var promises = new Array();
  95075. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  95076. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  95077. var deferred = new BABYLON.Deferred();
  95078. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  95079. if (!_this._disposed) {
  95080. deferred.resolve();
  95081. }
  95082. }, function (message, exception) {
  95083. if (!_this._disposed) {
  95084. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  95085. }
  95086. });
  95087. promises.push(deferred.promise);
  95088. babylonTexture.name = texture.name || "texture" + texture._index;
  95089. babylonTexture.wrapU = samplerData.wrapU;
  95090. babylonTexture.wrapV = samplerData.wrapV;
  95091. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  95092. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  95093. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  95094. babylonTexture.updateURL(objectURL);
  95095. }));
  95096. assign(babylonTexture);
  95097. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  95098. return Promise.all(promises).then(function () { });
  95099. };
  95100. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  95101. if (!sampler._data) {
  95102. sampler._data = {
  95103. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  95104. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  95105. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  95106. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  95107. };
  95108. }
  95109. ;
  95110. return sampler._data;
  95111. };
  95112. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  95113. if (image._objectURL) {
  95114. return image._objectURL;
  95115. }
  95116. var promise;
  95117. if (image.uri) {
  95118. promise = this._loadUriAsync(context, image.uri);
  95119. }
  95120. else {
  95121. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  95122. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  95123. }
  95124. image._objectURL = promise.then(function (data) {
  95125. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  95126. });
  95127. return image._objectURL;
  95128. };
  95129. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  95130. var _this = this;
  95131. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  95132. if (promise) {
  95133. return promise;
  95134. }
  95135. if (!GLTFLoader._ValidateUri(uri)) {
  95136. throw new Error(context + ": Uri '" + uri + "' is invalid");
  95137. }
  95138. if (BABYLON.Tools.IsBase64(uri)) {
  95139. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  95140. }
  95141. return new Promise(function (resolve, reject) {
  95142. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  95143. if (!_this._disposed) {
  95144. resolve(new Uint8Array(data));
  95145. }
  95146. }, function (event) {
  95147. if (!_this._disposed) {
  95148. try {
  95149. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  95150. request._lengthComputable = event.lengthComputable;
  95151. request._loaded = event.loaded;
  95152. request._total = event.total;
  95153. _this._onProgress();
  95154. }
  95155. }
  95156. catch (e) {
  95157. reject(e);
  95158. }
  95159. }
  95160. }, _this._babylonScene.database, true, function (request, exception) {
  95161. if (!_this._disposed) {
  95162. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  95163. }
  95164. });
  95165. _this._requests.push(request);
  95166. });
  95167. };
  95168. GLTFLoader.prototype._onProgress = function () {
  95169. if (!this._progressCallback) {
  95170. return;
  95171. }
  95172. var lengthComputable = true;
  95173. var loaded = 0;
  95174. var total = 0;
  95175. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  95176. var request = _a[_i];
  95177. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  95178. return;
  95179. }
  95180. lengthComputable = lengthComputable && request._lengthComputable;
  95181. loaded += request._loaded;
  95182. total += request._total;
  95183. }
  95184. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  95185. };
  95186. GLTFLoader._GetProperty = function (context, array, index) {
  95187. if (!array || index == undefined || !array[index]) {
  95188. throw new Error(context + ": Failed to find index (" + index + ")");
  95189. }
  95190. return array[index];
  95191. };
  95192. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  95193. // Set defaults if undefined
  95194. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  95195. switch (mode) {
  95196. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  95197. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  95198. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  95199. default:
  95200. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  95201. return BABYLON.Texture.WRAP_ADDRESSMODE;
  95202. }
  95203. };
  95204. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  95205. // Set defaults if undefined
  95206. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  95207. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  95208. if (magFilter === 9729 /* LINEAR */) {
  95209. switch (minFilter) {
  95210. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  95211. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  95212. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  95213. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  95214. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  95215. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  95216. default:
  95217. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  95218. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  95219. }
  95220. }
  95221. else {
  95222. if (magFilter !== 9728 /* NEAREST */) {
  95223. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  95224. }
  95225. switch (minFilter) {
  95226. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  95227. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  95228. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  95229. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  95230. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  95231. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  95232. default:
  95233. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  95234. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  95235. }
  95236. }
  95237. };
  95238. GLTFLoader._GetNumComponents = function (context, type) {
  95239. switch (type) {
  95240. case "SCALAR": return 1;
  95241. case "VEC2": return 2;
  95242. case "VEC3": return 3;
  95243. case "VEC4": return 4;
  95244. case "MAT2": return 4;
  95245. case "MAT3": return 9;
  95246. case "MAT4": return 16;
  95247. }
  95248. throw new Error(context + ": Invalid type (" + type + ")");
  95249. };
  95250. GLTFLoader._ValidateUri = function (uri) {
  95251. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  95252. };
  95253. GLTFLoader._GetDrawMode = function (context, mode) {
  95254. mode = mode || 4 /* TRIANGLES */;
  95255. switch (mode) {
  95256. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  95257. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  95258. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  95259. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  95260. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  95261. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  95262. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  95263. }
  95264. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  95265. };
  95266. GLTFLoader.prototype._compileMaterialsAsync = function () {
  95267. var promises = new Array();
  95268. if (this._gltf.materials) {
  95269. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  95270. var material = _a[_i];
  95271. if (material._babylonData) {
  95272. for (var babylonDrawMode in material._babylonData) {
  95273. var babylonData = material._babylonData[babylonDrawMode];
  95274. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  95275. var babylonMesh = _c[_b];
  95276. // Ensure nonUniformScaling is set if necessary.
  95277. babylonMesh.computeWorldMatrix(true);
  95278. var babylonMaterial = babylonData.material;
  95279. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  95280. if (this.useClipPlane) {
  95281. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  95282. }
  95283. }
  95284. }
  95285. }
  95286. }
  95287. }
  95288. return Promise.all(promises).then(function () { });
  95289. };
  95290. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  95291. var promises = new Array();
  95292. var lights = this._babylonScene.lights;
  95293. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  95294. var light = lights_1[_i];
  95295. var generator = light.getShadowGenerator();
  95296. if (generator) {
  95297. promises.push(generator.forceCompilationAsync());
  95298. }
  95299. }
  95300. return Promise.all(promises).then(function () { });
  95301. };
  95302. GLTFLoader.prototype._clear = function () {
  95303. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  95304. var request = _a[_i];
  95305. request.abort();
  95306. }
  95307. this._requests.length = 0;
  95308. if (this._gltf && this._gltf.images) {
  95309. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  95310. var image = _c[_b];
  95311. if (image._objectURL) {
  95312. image._objectURL.then(function (value) {
  95313. URL.revokeObjectURL(value);
  95314. });
  95315. image._objectURL = undefined;
  95316. }
  95317. }
  95318. }
  95319. delete this._gltf;
  95320. delete this._babylonScene;
  95321. this._completePromises.length = 0;
  95322. for (var name_4 in this._extensions) {
  95323. this._extensions[name_4].dispose();
  95324. }
  95325. this._extensions = {};
  95326. delete this._rootBabylonMesh;
  95327. delete this._progressCallback;
  95328. this.onMeshLoadedObservable.clear();
  95329. this.onTextureLoadedObservable.clear();
  95330. this.onMaterialLoadedObservable.clear();
  95331. };
  95332. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  95333. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  95334. var name_5 = _a[_i];
  95335. var extension = this._extensions[name_5];
  95336. if (extension.enabled) {
  95337. var promise = actionAsync(extension);
  95338. if (promise) {
  95339. return promise;
  95340. }
  95341. }
  95342. }
  95343. return null;
  95344. };
  95345. GLTFLoader._Names = new Array();
  95346. GLTFLoader._Factories = {};
  95347. return GLTFLoader;
  95348. }());
  95349. GLTF2.GLTFLoader = GLTFLoader;
  95350. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  95351. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95352. })(BABYLON || (BABYLON = {}));
  95353. //# sourceMappingURL=babylon.glTFLoader.js.map
  95354. "use strict";
  95355. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  95356. var BABYLON;
  95357. (function (BABYLON) {
  95358. var GLTF2;
  95359. (function (GLTF2) {
  95360. var GLTFLoaderExtension = /** @class */ (function () {
  95361. function GLTFLoaderExtension(loader) {
  95362. this.enabled = true;
  95363. this._loader = loader;
  95364. }
  95365. GLTFLoaderExtension.prototype.dispose = function () {
  95366. delete this._loader;
  95367. };
  95368. // #region Overridable Methods
  95369. /** Override this method to modify the default behavior for loading scenes. */
  95370. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  95371. /** Override this method to modify the default behavior for loading nodes. */
  95372. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  95373. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  95374. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  95375. /** Override this method to modify the default behavior for loading materials. */
  95376. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  95377. /** Override this method to modify the default behavior for loading uris. */
  95378. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  95379. // #endregion
  95380. /** Helper method called by a loader extension to load an glTF extension. */
  95381. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  95382. if (!property.extensions) {
  95383. return null;
  95384. }
  95385. var extensions = property.extensions;
  95386. var extension = extensions[this.name];
  95387. if (!extension) {
  95388. return null;
  95389. }
  95390. // Clear out the extension before executing the action to avoid recursing into the same property.
  95391. delete extensions[this.name];
  95392. try {
  95393. return actionAsync(context + "/extensions/" + this.name, extension);
  95394. }
  95395. finally {
  95396. // Restore the extension after executing the action.
  95397. extensions[this.name] = extension;
  95398. }
  95399. };
  95400. /** Helper method called by the loader to allow extensions to override loading scenes. */
  95401. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  95402. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  95403. };
  95404. /** Helper method called by the loader to allow extensions to override loading nodes. */
  95405. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  95406. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  95407. };
  95408. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  95409. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  95410. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  95411. };
  95412. /** Helper method called by the loader to allow extensions to override loading materials. */
  95413. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  95414. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  95415. };
  95416. /** Helper method called by the loader to allow extensions to override loading uris. */
  95417. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  95418. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  95419. };
  95420. return GLTFLoaderExtension;
  95421. }());
  95422. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  95423. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95424. })(BABYLON || (BABYLON = {}));
  95425. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  95426. "use strict";
  95427. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  95428. var BABYLON;
  95429. (function (BABYLON) {
  95430. var GLTF2;
  95431. (function (GLTF2) {
  95432. var Extensions;
  95433. (function (Extensions) {
  95434. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  95435. var NAME = "MSFT_lod";
  95436. var MSFT_lod = /** @class */ (function (_super) {
  95437. __extends(MSFT_lod, _super);
  95438. function MSFT_lod() {
  95439. var _this = _super !== null && _super.apply(this, arguments) || this;
  95440. _this.name = NAME;
  95441. /**
  95442. * Maximum number of LODs to load, starting from the lowest LOD.
  95443. */
  95444. _this.maxLODsToLoad = Number.MAX_VALUE;
  95445. _this._loadingNodeLOD = null;
  95446. _this._loadNodeSignals = {};
  95447. _this._loadingMaterialLOD = null;
  95448. _this._loadMaterialSignals = {};
  95449. return _this;
  95450. }
  95451. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  95452. var _this = this;
  95453. return this._loadExtensionAsync(context, node, function (context, extension) {
  95454. var firstPromise;
  95455. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  95456. var _loop_1 = function (indexLOD) {
  95457. var nodeLOD = nodeLODs[indexLOD];
  95458. if (indexLOD !== 0) {
  95459. _this._loadingNodeLOD = nodeLOD;
  95460. if (!_this._loadNodeSignals[nodeLOD._index]) {
  95461. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  95462. }
  95463. }
  95464. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  95465. if (indexLOD !== 0) {
  95466. var previousNodeLOD = nodeLODs[indexLOD - 1];
  95467. if (previousNodeLOD._babylonMesh) {
  95468. previousNodeLOD._babylonMesh.dispose();
  95469. delete previousNodeLOD._babylonMesh;
  95470. }
  95471. }
  95472. if (indexLOD !== nodeLODs.length - 1) {
  95473. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  95474. if (_this._loadNodeSignals[nodeIndex]) {
  95475. _this._loadNodeSignals[nodeIndex].resolve();
  95476. delete _this._loadNodeSignals[nodeIndex];
  95477. }
  95478. }
  95479. });
  95480. if (indexLOD === 0) {
  95481. firstPromise = promise;
  95482. }
  95483. else {
  95484. _this._loader._completePromises.push(promise);
  95485. _this._loadingNodeLOD = null;
  95486. }
  95487. };
  95488. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  95489. _loop_1(indexLOD);
  95490. }
  95491. return firstPromise;
  95492. });
  95493. };
  95494. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  95495. var _this = this;
  95496. // Don't load material LODs if already loading a node LOD.
  95497. if (this._loadingNodeLOD) {
  95498. return null;
  95499. }
  95500. return this._loadExtensionAsync(context, material, function (context, extension) {
  95501. var firstPromise;
  95502. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  95503. var _loop_2 = function (indexLOD) {
  95504. var materialLOD = materialLODs[indexLOD];
  95505. if (indexLOD !== 0) {
  95506. _this._loadingMaterialLOD = materialLOD;
  95507. if (!_this._loadMaterialSignals[materialLOD._index]) {
  95508. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  95509. }
  95510. }
  95511. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  95512. if (indexLOD !== 0) {
  95513. var babylonDataLOD = materialLOD._babylonData;
  95514. assign(babylonDataLOD[babylonDrawMode].material);
  95515. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  95516. if (previousBabylonDataLOD[babylonDrawMode]) {
  95517. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  95518. delete previousBabylonDataLOD[babylonDrawMode];
  95519. }
  95520. }
  95521. if (indexLOD !== materialLODs.length - 1) {
  95522. var materialIndex = materialLODs[indexLOD + 1]._index;
  95523. if (_this._loadMaterialSignals[materialIndex]) {
  95524. _this._loadMaterialSignals[materialIndex].resolve();
  95525. delete _this._loadMaterialSignals[materialIndex];
  95526. }
  95527. }
  95528. });
  95529. if (indexLOD === 0) {
  95530. firstPromise = promise;
  95531. }
  95532. else {
  95533. _this._loader._completePromises.push(promise);
  95534. _this._loadingMaterialLOD = null;
  95535. }
  95536. };
  95537. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  95538. _loop_2(indexLOD);
  95539. }
  95540. return firstPromise;
  95541. });
  95542. };
  95543. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  95544. var _this = this;
  95545. // Defer the loading of uris if loading a material or node LOD.
  95546. if (this._loadingMaterialLOD) {
  95547. var index = this._loadingMaterialLOD._index;
  95548. return this._loadMaterialSignals[index].promise.then(function () {
  95549. return _this._loader._loadUriAsync(context, uri);
  95550. });
  95551. }
  95552. else if (this._loadingNodeLOD) {
  95553. var index = this._loadingNodeLOD._index;
  95554. return this._loadNodeSignals[index].promise.then(function () {
  95555. return _this._loader._loadUriAsync(context, uri);
  95556. });
  95557. }
  95558. return null;
  95559. };
  95560. /**
  95561. * Gets an array of LOD properties from lowest to highest.
  95562. */
  95563. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  95564. if (this.maxLODsToLoad <= 0) {
  95565. throw new Error("maxLODsToLoad must be greater than zero");
  95566. }
  95567. var properties = new Array();
  95568. for (var i = ids.length - 1; i >= 0; i--) {
  95569. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  95570. if (properties.length === this.maxLODsToLoad) {
  95571. return properties;
  95572. }
  95573. }
  95574. properties.push(property);
  95575. return properties;
  95576. };
  95577. return MSFT_lod;
  95578. }(GLTF2.GLTFLoaderExtension));
  95579. Extensions.MSFT_lod = MSFT_lod;
  95580. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  95581. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  95582. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95583. })(BABYLON || (BABYLON = {}));
  95584. //# sourceMappingURL=MSFT_lod.js.map
  95585. "use strict";
  95586. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  95587. var BABYLON;
  95588. (function (BABYLON) {
  95589. var GLTF2;
  95590. (function (GLTF2) {
  95591. var Extensions;
  95592. (function (Extensions) {
  95593. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  95594. var NAME = "KHR_draco_mesh_compression";
  95595. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  95596. __extends(KHR_draco_mesh_compression, _super);
  95597. function KHR_draco_mesh_compression(loader) {
  95598. var _this = _super.call(this, loader) || this;
  95599. _this.name = NAME;
  95600. _this._dracoCompression = null;
  95601. // Disable extension if decoder is not available.
  95602. if (!BABYLON.DracoCompression.DecoderUrl) {
  95603. _this.enabled = false;
  95604. }
  95605. return _this;
  95606. }
  95607. KHR_draco_mesh_compression.prototype.dispose = function () {
  95608. if (this._dracoCompression) {
  95609. this._dracoCompression.dispose();
  95610. }
  95611. _super.prototype.dispose.call(this);
  95612. };
  95613. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  95614. var _this = this;
  95615. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  95616. if (primitive.mode != undefined) {
  95617. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  95618. primitive.mode !== 4 /* TRIANGLES */) {
  95619. throw new Error(context + ": Unsupported mode " + primitive.mode);
  95620. }
  95621. // TODO: handle triangle strips
  95622. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  95623. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  95624. }
  95625. }
  95626. var attributes = {};
  95627. var loadAttribute = function (name, kind) {
  95628. var uniqueId = extension.attributes[name];
  95629. if (uniqueId == undefined) {
  95630. return;
  95631. }
  95632. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  95633. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  95634. babylonMesh._delayInfo.push(kind);
  95635. }
  95636. attributes[kind] = uniqueId;
  95637. };
  95638. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  95639. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  95640. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  95641. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  95642. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  95643. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  95644. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  95645. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  95646. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  95647. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  95648. try {
  95649. if (!_this._dracoCompression) {
  95650. _this._dracoCompression = new BABYLON.DracoCompression();
  95651. }
  95652. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  95653. }
  95654. catch (e) {
  95655. throw new Error(context + ": " + e.message);
  95656. }
  95657. });
  95658. });
  95659. };
  95660. return KHR_draco_mesh_compression;
  95661. }(GLTF2.GLTFLoaderExtension));
  95662. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  95663. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  95664. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  95665. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95666. })(BABYLON || (BABYLON = {}));
  95667. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  95668. "use strict";
  95669. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  95670. var BABYLON;
  95671. (function (BABYLON) {
  95672. var GLTF2;
  95673. (function (GLTF2) {
  95674. var Extensions;
  95675. (function (Extensions) {
  95676. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  95677. var NAME = "KHR_materials_pbrSpecularGlossiness";
  95678. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  95679. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  95680. function KHR_materials_pbrSpecularGlossiness() {
  95681. var _this = _super !== null && _super.apply(this, arguments) || this;
  95682. _this.name = NAME;
  95683. return _this;
  95684. }
  95685. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  95686. var _this = this;
  95687. return this._loadExtensionAsync(context, material, function (context, extension) {
  95688. material._babylonData = material._babylonData || {};
  95689. var babylonData = material._babylonData[babylonDrawMode];
  95690. if (!babylonData) {
  95691. var promises = new Array();
  95692. var name_1 = material.name || "materialSG_" + material._index;
  95693. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  95694. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  95695. promises.push(_this._loadSpecularGlossinessPropertiesAsync(context, material, extension, babylonMaterial));
  95696. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  95697. babylonData = {
  95698. material: babylonMaterial,
  95699. meshes: [],
  95700. loaded: Promise.all(promises).then(function () { })
  95701. };
  95702. material._babylonData[babylonDrawMode] = babylonData;
  95703. }
  95704. babylonData.meshes.push(babylonMesh);
  95705. assign(babylonData.material);
  95706. return babylonData.loaded;
  95707. });
  95708. };
  95709. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  95710. var promises = new Array();
  95711. if (properties.diffuseFactor) {
  95712. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  95713. babylonMaterial.alpha = properties.diffuseFactor[3];
  95714. }
  95715. else {
  95716. babylonMaterial.albedoColor = BABYLON.Color3.White();
  95717. }
  95718. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  95719. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  95720. if (properties.diffuseTexture) {
  95721. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  95722. babylonMaterial.albedoTexture = texture;
  95723. }));
  95724. }
  95725. if (properties.specularGlossinessTexture) {
  95726. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  95727. babylonMaterial.reflectivityTexture = texture;
  95728. }));
  95729. babylonMaterial.reflectivityTexture.hasAlpha = true;
  95730. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  95731. }
  95732. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  95733. return Promise.all(promises).then(function () { });
  95734. };
  95735. return KHR_materials_pbrSpecularGlossiness;
  95736. }(GLTF2.GLTFLoaderExtension));
  95737. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  95738. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  95739. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  95740. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95741. })(BABYLON || (BABYLON = {}));
  95742. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  95743. "use strict";
  95744. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  95745. var BABYLON;
  95746. (function (BABYLON) {
  95747. var GLTF2;
  95748. (function (GLTF2) {
  95749. var Extensions;
  95750. (function (Extensions) {
  95751. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  95752. var NAME = "KHR_lights";
  95753. var LightType;
  95754. (function (LightType) {
  95755. LightType["AMBIENT"] = "ambient";
  95756. LightType["DIRECTIONAL"] = "directional";
  95757. LightType["POINT"] = "point";
  95758. LightType["SPOT"] = "spot";
  95759. })(LightType || (LightType = {}));
  95760. var KHR_lights = /** @class */ (function (_super) {
  95761. __extends(KHR_lights, _super);
  95762. function KHR_lights() {
  95763. var _this = _super !== null && _super.apply(this, arguments) || this;
  95764. _this.name = NAME;
  95765. return _this;
  95766. }
  95767. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  95768. var _this = this;
  95769. return this._loadExtensionAsync(context, scene, function (context, extension) {
  95770. var promise = _this._loader._loadSceneAsync(context, scene);
  95771. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  95772. if (light.type !== LightType.AMBIENT) {
  95773. throw new Error(context + ": Only ambient lights are allowed on a scene");
  95774. }
  95775. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  95776. return promise;
  95777. });
  95778. };
  95779. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  95780. var _this = this;
  95781. return this._loadExtensionAsync(context, node, function (context, extension) {
  95782. var promise = _this._loader._loadNodeAsync(context, node);
  95783. var babylonLight;
  95784. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  95785. var name = node._babylonMesh.name;
  95786. switch (light.type) {
  95787. case LightType.AMBIENT: {
  95788. throw new Error(context + ": Ambient lights are not allowed on a node");
  95789. }
  95790. case LightType.DIRECTIONAL: {
  95791. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  95792. break;
  95793. }
  95794. case LightType.POINT: {
  95795. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  95796. break;
  95797. }
  95798. case LightType.SPOT: {
  95799. var spotLight = light;
  95800. // TODO: support inner and outer cone angles
  95801. //const innerConeAngle = spotLight.innerConeAngle || 0;
  95802. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  95803. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  95804. break;
  95805. }
  95806. default: {
  95807. throw new Error(context + ": Invalid light type (" + light.type + ")");
  95808. }
  95809. }
  95810. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  95811. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  95812. babylonLight.parent = node._babylonMesh;
  95813. return promise;
  95814. });
  95815. };
  95816. Object.defineProperty(KHR_lights.prototype, "_lights", {
  95817. get: function () {
  95818. var extensions = this._loader._gltf.extensions;
  95819. if (!extensions || !extensions[this.name]) {
  95820. throw new Error("#/extensions: '" + this.name + "' not found");
  95821. }
  95822. var extension = extensions[this.name];
  95823. return extension.lights;
  95824. },
  95825. enumerable: true,
  95826. configurable: true
  95827. });
  95828. return KHR_lights;
  95829. }(GLTF2.GLTFLoaderExtension));
  95830. Extensions.KHR_lights = KHR_lights;
  95831. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  95832. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  95833. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  95834. })(BABYLON || (BABYLON = {}));
  95835. //# sourceMappingURL=KHR_lights.js.map
  95836. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  95837. globalObject["BABYLON"] = BABYLON;
  95838. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var GridMaterial = BABYLON.GridMaterial;var GLTFFileLoader = BABYLON.GLTFFileLoader;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;var GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode ;var GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode ;var GLTFLoaderState = BABYLON.GLTFLoaderState ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF1 = BABYLON.GLTF1 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;var GLTF2 = BABYLON.GLTF2 ;
  95839. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,JoystickAxis ,SimplificationType ,AssetTaskState ,GLTFLoaderCoordinateSystemMode ,GLTFLoaderAnimationStartMode ,GLTFLoaderState ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF1 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 ,GLTF2 };